본문 바로가기
Algorithm/📖Baekjoon

#1302 베스트셀러

by yewoneeee 2022. 7. 24.

# 문제

# 입력 및 출력

# 풀이

map을 쓰면 편할 것 같아서 map을 썼다

근데 map은 기본적으로 key 값을 중심으로 오름차순 정렬된다

value 값에 책이 얼마나 팔렸는지 수량을 저장하려고 하다보니

책이 많이 팔린 순서대로 정렬되는 것이 아니고 책 이름의 알파벳 순으로 정렬되었다

 

따라서 입력 받을 때 가장 많이 팔린 책 개수를 저장해두고 알파벳 순으로 정렬된 map을 하나씩 읽으면서

가장 많이 팔린 책 개수 변수와 value 값이 일치하면 출력하고 종료하도록 했음

어처피 책 한권만 출력해야하기 때문에 한 번 출력하면 바로 종료하면 됨

#include <iostream>
#include <string>
#include <map>
using namespace std;
map<string, int> m;

int main() {
	int n, max = 0;
	cin >> n;
	string str;
	while (n--) {
		cin >> str;
		m[str]++;
		max = max < m[str] ? m[str] : max;
	}
	for (map<string, int>::iterator iter = m.begin(); iter != m.end(); iter++) {
		if (iter->second == max) {
			cout << iter->first << "\n";
			break;
		}
	}
}

처음엔 map 전체를 조회하기 위해 iterator를 사용했다

iterator 대신에 auto도 사용 가능하다

 

#include <iostream>
#include <string>
#include <map>
using namespace std;
map<string, int> m;

int main() {
	int n, max = 0;
	cin >> n;
	string str;
	while (n--) {
		cin >> str;
		m[str]++;
		max = max < m[str] ? m[str] : max;
	}
	for (auto t : m) {
		if (t.second == max) {
			cout << t.first << "\n";
			break;
		}
	}
}

 

'Algorithm > 📖Baekjoon' 카테고리의 다른 글

#6603 로또  (0) 2022.08.02
#4796 캠핑  (0) 2022.07.25
#14501 퇴사  (0) 2022.07.22
#24479 알고리즘 수업 - 깊이 우선 탐색 1  (0) 2022.07.17
#1914 하노이 탑  (0) 2022.07.11

댓글