반응형
C++
- map 대신 pair 사용.
#include <iostream>
#include <algorithm>
using namespace std;
void split(string S, pair<string, int> *P, int T)
{
int cnt = 1, i = 0;
for (char c : S)
if (c == ' ')
cnt++;
string arr[cnt];
for (char c : S)
if (c == ' ')
i++;
else
arr[i] += c;
for (auto s : arr)
for (int k = 0; k < T; k++)
if (P[k].first == s)
P[k].second++;
}
bool cmd(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()
{
cin.tie(0)->sync_with_stdio(0);
int T, i = -1;
cin >> T;
pair<string, int> P[T];
string s;
while (++i < T)
{
cin >> s;
P[i] = {s, 0};
}
i = -1;
cin.ignore();
while (++i < T)
{
getline(cin, s);
split(s, P, T);
}
sort(P, P + T, cmd);
for (auto a : P)
cout << a.first << " " << a.second << "\\n";
}
C++
- unordered_map과 vector 사용.
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <vector>
using namespace std;
void split(string S, unordered_map<string, int> &M, int T)
{
int cnt = 1, i = 0;
for (char c : S)
if (c == ' ')
cnt++;
string str[cnt];
for (char c : S)
if (c == ' ')
i++;
else
str[i] += c;
for (auto s : str)
M[s]++;
}
bool cmd(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()
{
cin.tie(0)->sync_with_stdio(0);
int T, i = -1;
cin >> T;
unordered_map<string, int> M;
string s;
while (++i < T)
{
cin >> s;
M[s] = 0;
}
i = -1;
cin.ignore();
while (++i < T)
{
getline(cin, s);
split(s, M, T);
}
vector<pair<string, int>> V(M.begin(), M.end());
sort(V.begin(), V.end(), cmd);
for (auto a : V)
cout << a.first << " " << a.second << "\\n";
}
반응형
'Algorithm > Data Structure' 카테고리의 다른 글
[BOJ 20920] S3 영단어 암기는 괴로워 { C++ } (0) | 2022.07.04 |
---|---|
[BOJ 1302] S4 베스트 셀러 {C++} (0) | 2022.07.02 |
[BOJ 9733] S5 꿀벌 {C++} (0) | 2022.07.01 |
[BOJ 16499] S4 동일한 단어 그룹화하기 {C++} (0) | 2022.06.30 |
[ BOJ 5568 ] S4 카드 놓기 { C++ } (0) | 2022.06.25 |