a743: 10420 - List of Conquests

  1. 1. 內容
  2. 2. 範例輸入
  3. 3. 範例輸出
  4. 4. 想法
  5. 5. 程式碼

CPE 一顆星選集 49 道必考題

題目連結:https://zerojudge.tw/ShowProblem?problemid=a743

內容

給定一整數 n (n <= 2000)代表有 n 列,每列有多個字串,計算每列第一個字串出現的次數,並按照字典序排序。

範例輸入

3
Spain Donna Elvira
England Jane Doe
Spain Donna Anna

範例輸出

England 1
Spain 2

想法

使用 getline 一次讀取一列,接著用 stringstream 將第一個字串分割出來,存入 map 計算次數,利用 map 的特性(字串默認排序為字典序),遍歷一次即可。

程式碼

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr)
using namespace std;

int main(){
fastio;
int n;
string s, country;
stringstream ss;
map <string, int> mp;
map <string, int> ::iterator iter;
cin >> n >> ws;
while(n--){
getline(cin, s);
ss << s;
ss >> country;
++mp[country];
ss.str(""), ss.clear();
}
for(iter = mp.begin(); iter != mp.end(); ++iter){
cout << iter -> first << " " << iter -> second << "\n";
}
return 0;
}