熱門文章

2026年1月27日 星期二

ZeroJudge 解題筆記:c012. 10062 - Tell me the frequencies!

作者:王一哲
日期:2026年1月27日


ZeroJudge 題目連結:c012. 10062 - Tell me the frequencies!

解題想法


這題如果用 Python 解題,可以用預設的 map 或是 collections 函式庫中的 Counter 計數,用 Counter 比較方便,只要寫 Counter(字串) 就可以算出字串每個字元的個數。測資會有空白,如果用 C++ 要用 getline 讀取資料,但是不能計算到結尾的 \n 或 \r。

Python 程式碼


使用時間約為 12 ms,記憶體約為 3.3 MB,通過測試。
from collections import Counter
import sys

first = True
for line in sys.stdin:
    if not first: print()
    first = False
    cnt = Counter(line.strip())
    ans = [(v, ord(k)) for k, v in cnt.items()]
    ans.sort(key = lambda x : (x[0], -x[1]))
    for a in ans: print(a[1], a[0])

使用時間約為 18 ms,記憶體約為 3.2 MB,通過測試。
from collections import Counter
import sys

result = []
lines = sys.stdin.readlines()
for line in lines:
    if result: result.append("\n")
    cnt = Counter(line.strip())
    ans = [(v, ord(k)) for k, v in cnt.items()]
    ans.sort(key = lambda x : (x[0], -x[1]))
    for a in ans: result.append(f"{a[1]:d} {a[0]:d}\n")
sys.stdout.write("".join(result))


C++ 程式碼


使用時間約為 2 ms,記憶體約為 344 kB,通過測試。
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    bool first = true;
    string s;
    while(getline(cin, s)) {
        if (!first) cout << "\n";
        first = false;
        map<char, int> cnt;
        for(char c : s) {
            if (c == '\n' || c == '\r') continue;
            cnt[c]++;
        }
        vector<pair<int, int>> ans;  // ASCII code, number
        for(auto it : cnt) ans.push_back(make_pair((int)it.first, it.second));
        sort(ans.begin(), ans.end(), [](pair<int, int> a, pair<int, int> b) {
            if (a.second == b.second) return a.first > b.first;
            return a.second < b.second; } );
        for(auto it : ans) cout << it.first << " " << it.second << "\n";
    }
    return 0;
}


沒有留言:

張貼留言