나도 공부한다/알고리즘

[백준] 1302. 베스트셀러 (C++)

꾸빵이 2023. 4. 30. 20:56

Level

실버4

 

Key Point

개수가 같으면 사전 순으로 앞에 있는 것을 출력한다.

 

Idea

입력이 문자열이고 책의 개수를 카운팅하는 문제다. 입력이 숫자였으면 카운팅 정렬을 선택했을텐데... 문자열이라 벡터와 map 중에 고민했다. 개수가 같으면 사전 순으로 앞에 있는 걸 출력하라는 조건때문에 map을 선택했다. map은 알아서 오름차순 정렬이 되기 때문이다. 조건문만 신경써서 잘 써주면 된다.

 

Code

#include <iostream>
#include <algorithm>
#include <map>
#include <string>

using namespace std;

int main() {

	ios::sync_with_stdio(false);
	cin.tie(NULL);

	int n = 0;
	int max = 0;
	string st = "";
	string result = "";
	map<string, int>mp;
	
	cin >> n;

	for (int i = 0; i < n; i++) {
		cin >> st;
		if (mp.find(st) == mp.end()) { // 값이 없는 경우
			mp.insert({ st,1 });
		}
		else {
			mp[st]++;
		}
		
	}

	for (pair<string, int>p : mp) {
		if (max < p.second) {
			max = p.second;
			result = p.first;
		} // 이미 사전순으로 정렬되어 있기 때문에 다음 p.second가 max와 같으면 if문 안에 들어가지 않음. 사전순 출력 성공.
	}

	cout << result;

	return 0;
}