string을 key로 하고, int를 value로 한다.
팔린 책의 개수인 second 개수가 가장 큰 값을 res에 넣는다.
가장 많이 팔린 책이 여러 개일 경우에는 사전 순으로 가장 앞서는 제목을 출력해야 되니
팔린 책의 개수인 second 개수가 res일 경우에 first인 key를 출력해주고 함수를 끝낸다.
(map은 삽입이 되면서 오름차순으로 자동 정렬된다.)
반복문 데이터 접근
- 인덱스 기반
for(auto iter = m.begin(); iter != m.end(); iter++){
cout << iter->first << " " << iter->second << "\n";
}
- 반복문 기반
for(auto iter:m){
cout << iter.first << " " << iter.second << "\n";
}
방법1 (인덱스 기반)
#include <algorithm>
#include <iostream>
#include <string>
#include <map>
using namespace std;
int N;
string book;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL), cout.tie(NULL);
cin >> N;
map <string, int> m;
while(N--){
cin >> book;
m[book]++;
}
int res = 0;
for (auto i = m.begin(); i != m.end(); i++) {
res = max(res, i->second);
}
for (auto i = m.begin(); i != m.end(); i++) {
if (res == i->second) {
cout << i->first;
return 0;
}
}
}
방법2 (반복문 기반)
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <string>
#include <map>
using namespace std;
int N;
string book;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL), cout.tie(NULL);
cin >> N;
map <string, int> m;
while(N--){
cin >> book;
m[book]++;
}
int res = 0;
for (auto i:m) {
res = max(res, i.second);
}
for (auto i:m) {
if (res == i.second) {
cout << i.first;
return 0;
}
}
}
'🍞 Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 14425 문자열 집합 c++ (0) | 2022.09.13 |
---|---|
[백준] 1620 나는야 포켓몬 마스터 이다솜 c++ (0) | 2022.09.13 |
[백준] 4803 트리 c++ (0) | 2022.09.05 |
[백준] 15809 전국시대 c++ (0) | 2022.09.05 |
[백준] 1939 중량제한 c++ (0) | 2022.09.05 |