日期:2025年12月7日
ZeroJudge 題目連結:m702. 傑出校友票選活動
解題想法
這題用字典計數比較方便。如果用 Python 解題,可以用預設的 dict 計數,再將 dict 的 (value, key) 組成 tuple 存入另一個 list,將 list 依照 value 由大到小排序;也可以先將所有的選票儲存到一個串列中,用 collections.Counter 計數,最後用 Counter 的功能 most_common 取出前 m 個最大的值。
Python 程式碼
使用預設的 dict,使用時間約為 0.2 s,記憶體約為 27.1 MB,通過測試。
n, m = map(int, input().split())
cnt = dict()
for _ in range(n):
name = input()
if name not in cnt: cnt[name] = 1
else: cnt[name] += 1
ballot = sorted([(val, name) for name, val in cnt.items()], reverse=True)
print(" ".join([name for _, name in ballot[:m]]))
使用 Counter,使用時間約為 67 ms,記憶體約為 20.3 MB,通過測試。
from collections import Counter
n, m = map(int, input().split())
ballot = [input() for _ in range(n)]
cnt = Counter(ballot)
print(*[name for name, _ in cnt.most_common(m)])
C++ 程式碼
使用時間約為 52 ms,記憶體約為 16.8 MB,通過測試。
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <utility>
#include <algorithm>
#include <functional>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int n, m; cin >> n >> m;
map<string, int> cnt;
for(int i=0; i<n; i++) {
string s; cin >> s;
cnt[s]++;
}
vector<pair<int, string>> ballot;
for(auto it : cnt) {
ballot.push_back(make_pair(it.second, it.first));
}
sort(ballot.begin(), ballot.end(), greater<pair<int, string>> ());
for(int i=0; i<m; i++) cout << ballot[i].second << " \n"[i == m-1];
return 0;
}
沒有留言:
張貼留言