a826簡單字元直方圖與頻率質數篩

CPE:Prime Frequency (UVa 10789)

依 ASCII 順序列出次數為質數的字元。

前往題目練習 →回報教學錯誤預篩 O(U log log U),U=2000;每筆 O(n+128) 時間,空間 O(U+128)。

解題思路

字串長度最多 2000,先篩出 0 到 2000 中哪些頻率是質數,特別把 0、1 設為非質數。每筆建立字元次數表,逐一計數;大小寫各佔不同位置,不可先轉小寫。

最後按 ASCII 順序掃描字元,當 prime[count[ch]] 為真就加入答案。直接掃陣列或將符合條件的字元排序,都能滿足數字先於大寫、大寫先於小寫的順序。答案空字串時改輸出 empty,每筆標頭 Case k: 後恰有一個空白。

Step-by-step animation

示意:AABBBcccc

回報動畫錯誤
步驟 1 / 3

統計

A 有 2 次,B 有 3 次,c 有 4 次。

A:2
B:3
c:4
字元總數
9

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
    vector<bool> prime(2001, true);
    prime[0] = prime[1] = false;
    for (int p = 2; p * p <= 2000; ++p)
        if (prime[p])
            for (int x = p * p; x <= 2000; x += p)
                prime[x] = false;
    int t;
    cin >> t;
    for (int tc = 1; tc <= t; ++tc) {
        string s, ans;
        cin >> s;
        int count[128] = {};
        for (unsigned char c : s)
            ++count[c];
        for (int c = 0; c < 128; ++c)
            if (prime[count[c]])
                ans += char(c);
        cout << "Case " << tc << ": " << (ans.empty() ? "empty" : ans) << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多