a202簡單計數、分類與統計

TOI 2019/04 新手組:滿意度調查

統計十種數字,依次數降序及數值升序輸出。

前往題目練習 →回報教學錯誤位數 L:時間 O(L+10 log 10),空間 O(L+10)。

這題在學什麼

將正整數當字串讀取,逐字統計 0 到 9 的出現次數。

只把次數大於 0 的數字加入候選,排序鍵為 (-次數, 數字)。

每種數字只輸出一次,不輸出次數本身;同頻時小數字優先。

Step-by-step animation

滿意度調查・頻率排序

回報動畫錯誤
步驟 1 / 3

統計 7727003

7 出現 3 次、0 出現 2 次、2 與 3 各一次。

7:3
0:2
2:1
3:1
不同數字
4

Reference solution

回報程式錯誤

完整程式

#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    string s;
    cin >> s;
    array<int, 10> cnt{};
    for (char c : s)
        cnt[c - '0']++;
    vector<int> v;
    for (int d = 0; d < 10; d++)
        if (cnt[d])
            v.push_back(d);
    sort(v.begin(), v.end(),
         [&](int x, int y) { return cnt[x] != cnt[y] ? cnt[x] > cnt[y] : x < y; });
    for (int i = 0; i < (int)v.size(); i++)
        cout << (i ? " " : "") << v[i];
    cout << '\n';
}

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

更多