日期:2026年1月17日
ZeroJudge 題目連結:a743. 10420 - List of Conquests
解題想法
這題用 map 及 set 儲存各國家的人名,讀取所有的測資之後,再將國家及人名數量組成 tuple 存入另一個 list 之中,將 list 依照人名數量由小到大排序,如果數量相同再依照國家名稱排序。
Python 程式碼
使用時間約為 23 ms,記憶體約為 4.2 MB,通過測試。
from collections import defaultdict
n = int(input())
cnt = defaultdict(set)
for _ in range(n):
country, name = list(input().split(" ", 1)) # 用空格分格,只切一次
cnt[country].add(name)
ans = sorted([(k, len(v)) for k, v in cnt.items()])
for a in ans: print(*a)
C++ 程式碼
使用時間約為 2 ms,記憶體約為 904 kB,通過測試。如果改用 unordered_map 及 unordered_set 反而比較慢,使用時間約為 6 ms,記憶體約為 1 MB,通過測試。
#include <iostream>
#include <map>
#include <string>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n; cin >> n;
map<string, set<string>> cnt;
for(int i=0; i<n; i++) {
string country, name;
cin >> country; cin.ignore();
getline(cin, name);
cnt[country].insert(name);
}
vector<pair<string, int>> ans;
for(auto it : cnt) ans.push_back(make_pair(it.first, (int)it.second.size()));
sort(ans.begin(), ans.end());
for(auto a : ans) cout << a.first << " " << a.second << "\n";
return 0;
}
沒有留言:
張貼留言