b183簡單

92 嘉義區資訊學科能力競賽(2003)|英文單字次數

掃描全文,將連續A到Z字母視為一個單字,其他符號作分隔。

解題思路

掃描全文,將連續A到Z字母視為一個單字,其他符號作分隔。

每遇分隔或EOF就把目前非空單字累加一次。

依(-次數,單字字典序)排序,得到次數遞減、同次數字典序遞增的要求。

字元數L、不同字W,時間 O(L+W log W)不含字串比較成本,空間 O(L)。

Step-by-step animation

教學小例:以非大寫字母斷詞的頻率表

回報動畫錯誤
步驟 1 / 3

文章A,B A.

掃描得到A、B、A

掃描得到A、B、A
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    map<string, int> c;
    string s;
    char x;
    while (cin.get(x)) {
        if (x >= 'A' && x <= 'Z')
            s += x;
        else if (!s.empty()) {
            c[s]++;
            s.clear();
        }
    }
    if (!s.empty())
        c[s]++;
    vector<pair<int, string>> a;
    for (auto [w, n] : c)
        a.push_back({-n, w});
    sort(a.begin(), a.end());
    for (auto [n, w] : a)
        cout << w << ": " << -n << '\n';
}

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

更多