熱門文章

2026年2月6日 星期五

ZeroJudge 解題筆記:c044. 10008 - What's Cryptanalysis

作者:王一哲
日期:2026年2月6日


ZeroJudge 題目連結:c044. 10008 - What's Cryptanalysis

解題想法


這題可以用表格或字典計數,以下的寫法採用表格計數,用一個長度為 26 的陣列記錄每個字母出現的次數,不是英文字母的字元不需要計數。計數完畢之後,再將次數、字母組成 tuple 或 pair 存入陣列之中,先依照次數由大到小排序,如果次數相同再依照字母由小到大排序。

Python 程式碼


使用時間約為 21 ms,記憶體約為 3.3 MB,通過測試。
n = int(input())
cnt = [0]*26
for _ in range(n):
    s = input()
    for c in s:
        if c.isupper():
            cnt[ord(c) - ord('A')] += 1
        elif c.islower():
            cnt[ord(c) - ord('a')] += 1
ans = [(v, chr(k+ord('A'))) for k, v in enumerate(cnt) if v > 0]
ans.sort(key = lambda x : (-x[0], ord(x[1])))
for a in ans: print(a[1], a[0])


C++ 程式碼


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

int main() {
    ios::sync_with_stdio(0); cin.tie(0);
    int n; cin >> n; cin.ignore();
    int cnt[26] = {0};
    string s;
    for(int i=0; i<n; i++) {
        s.clear();
        getline(cin, s);
        for(char c : s) {
            if (isupper(c)) cnt[c-'A']++;
            else if (islower(c)) cnt[c-'a']++;
        }
    }
    vector<pair<char, int>> ans;
    for(int i=0; i<26; i++) {
        if (cnt[i] > 0) ans.push_back(make_pair(char(i+'A'), cnt[i]));
    }
    sort(ans.begin(), ans.end(), [](pair<char, int> a, pair<char, 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;
}


沒有留言:

張貼留言