백준/해시

[백준] C++ 1302번 베스트셀러

2zreal 2024. 10. 1. 16:28

 

가장 많이 팔린 책의 이름을 출력하는 문제이다. 만약 많이 팔린 책이 여러 개이면 사전순으로 정렬해야 한다.

 

문제해결방법

1. HashMap을 사용해서 책이 몇 번 입력받았는지 저장한다. unordered_Map <string, int> hashMap

2. HashMap을 정렬할 수는 없으니 HashMap을 백터로 복사해서 백터를 정렬한다.

3. 백터를 정렬하면 string을 기준으로 사전순으로 정렬되기 때문에 for문을 돌면서 정렬된 백터의 가장 큰 값만 찾아주면 끝난다.

 

#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>

using namespace std;

int main(void)
{
	unordered_map<string, int> hashMap;
	int N = 0;
	cin >> N;

	for (int i = 0; i < N; i++)
	{
		string temp = "";
		cin >> temp;
		hashMap[temp]++;
	}

	vector<pair<string, int>> V(hashMap.begin(), hashMap.end());

	sort(V.begin(),V.end());

	int max = 0;
	string result = "";
	for (auto p : V)
	{
		if (p.second > max)
		{
			max = p.second;
			result = p.first;
		}
	}

	cout << result;

	return 0;
}