開啟章節選單
10062 Tell me the frequencies!
題目連結
題目敘述
給你一行文字,請你找出其中所有 ASCII 字元出現的次數。
每行輸入都會視為一組獨立的測資。
請注意,輸入字串中不會有 ASCII 前 32 個控制字元,也不會有 128 以上的字元(所以只有 32~127 這一段的 ASCII 字元,且不含結尾的換行符號 \n
或 \r
)。
輸入說明
- 多行文字,每一行都是一筆測資。
- 每行最多 1000 個字元。
- 輸入到檔案結束(EOF)為止。
輸出說明
- 對於每一組輸入,請輸出這一行所有出現過的 ASCII 字元的ASCII 編號及其出現次數。
- 輸出時:
- 先以次數由小到大排序。
- 如果次數相同,ASCII 值較大的字元排前面。
- 每組輸出之間要空一行。
- 不需輸出多餘的空白行。
解題思路
- 統計每個 ASCII 字元出現的次數
- 整理出現過的字元及其次數
- 依規則排序
程式碼
#include <bits/stdc++.h> #define f first #define s second using namespace std; int main(){ string s; int cnt = 0; while(getline(cin,s)){ if(cnt)cout<<endl; vector<int> vc(1e5,0); for(auto c:s)vc[c]+=1; vector<pair<int,int>> order; for(int i=0;i<1e5;i++){ if(vc[i]>0){ order.push_back({vc[i],i}); } } sort(begin(order),end(order),[](pair<int,int> a,pair<int,int> b){ if(a.f!=b.f)return a.f<b.f; return a.s>b.s; }); for(auto pr:order){ cout<<pr.s<<" "<<pr.f<<endl; } cnt++; } return 0; }