a746簡單頻率與反向 ASCII 的雙鍵排序
CPE:Tell me the frequencies! (UVa 10062)
對每行獨立統計並依題目順序列印。
解題思路
字元範圍固定為 ASCII 32–127,以計數陣列記每個字元出現次數。只把次數大於零的字元列入排序,排序鍵是 (次數,−ASCII),因此同次數時編碼較大者先印。
輸入逐行讀至 EOF,行內空白本身是 ASCII 32,必須統計,只有換行與歸位不計。每行資料分別輸出 ASCII 值及次數,兩組之間插入空行;不能把全篇文字的次數合在一起。
Step-by-step animation
示意:AABBC
步驟 1 / 3
統計
A 和 B 各 2 次,C 出現 1 次。
65:2
66:2
67:1
- 總字元
- 5
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string s;
bool first = true;
while (getline(cin, s)) {
int f[256] = {};
for (unsigned char c : s)
if (c != '\r')
++f[c];
vector<int> a;
for (int i = 32; i <= 127; ++i)
if (f[i])
a.push_back(i);
sort(a.begin(), a.end(), [&](int x, int y) { return f[x] != f[y] ? f[x] < f[y] : x > y; });
if (!first)
cout << '\n';
first = false;
for (int c : a)
cout << c << ' ' << f[c] << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。