[백준] 1302번 베스트셀러 / C++
#문제
#풀이
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<pair<string, int>> best;
bool Compair(pair<string, int> a, pair<string, int> b)
{
if (a.second == b.second)
{
return a.first < b.first;
}
return a.second > b.second;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
for (int i = 0; i < n; ++i)
{
string book;
cin >> book;
bool has = false;
int j = 0;
while (j < best.size())
{
if (best[j].first == book)
{
best[j].second++;
has = true;
break;
}
j++;
}
if (!has)
{
best.push_back(make_pair(book, 1));
}
}
sort(best.begin(), best.end(), Compair);
cout << best[0].first;
return 0;
}
#정리
n개의 팔린 책의 이름을 받고, 가장 많이 팔린 책의 이름을 출력하는 문제. 팔린 갯수가 같다면 알파벳이 빠른 책의 이름을 출력한다. vector로 책 이름(string)과 팔린 갯수(int)를 받는 컨테이너를 만들었다. 컨테이너 내에 책이 있는지 판단하여 갯수를 증가시켰고, 정렬 알고리즘을 사용하여 컨테이너를 정렬시킨 뒤 0번째 원소의 첫 번째 데이터를 출력하여 해결. Compair함수는 두 번째 데이터를 비교, 두 번째 데이터가 같다면 첫 번째 원소를 사전순으로 정렬할 수 있도록 만들었다.
Enjoy Reading This Article?
Here are some more articles you might like to read next: