백준/해시
[백준] C++ 4358번 생태학
2zreal
2024. 9. 29. 12:56
문제해결방법
1. 입력을 받으면서 count를 센다.(이번 문제는 입력의 개수를 제시하지 않아서 평소에 입력받던 데로 받으면 안 됨. getline() 함수를 통해 입력받아야 한다.)
2. 소수점 넷째 자리로 고정한다.(cout<<fixed; cout.precision(4))
3. unordered_map을 사용하면 vector로 데이터를 복사하고 sort함수를 통해 정렬해 준다.(map을 사용하면 vector로 데이터를 복사하고 sort함수를 사용할 필요가 없음.)
4. %로 변환해서 출력해준다.
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
unordered_map<string,int> hashMap;
int count = 0;
string s = "";
while (getline(cin,s))
{
hashMap[s]++;
count++;
}
vector <pair<string, int>> v(hashMap.begin(), hashMap.end());
sort(v.begin(), v.end());
cout << fixed;
cout.precision(4);
for (auto a : v)
{
cout << a.first << " " << (a.second * 100 /(float)count) << '\n';
}
}