CPE 一顆星選集 49 道必考題
題目連結:https://zerojudge.tw/ShowProblem?problemid=c012
內容
給定一字串,輸出各字元的ASCII值跟出現的次數(依次數由小到大,若一樣則ASCII較大者先輸出)。
範例輸入
AAABBC
122333
範例輸出
67 1
66 2
65 3
49 1
50 2
51 3
想法
使用 getline 一次讀取一列(可能有空白),開 struct 紀錄各個ASCII值和其出現次數,再照著題目要求排序即可。
程式碼
    
    
        1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
   | #include <bits/stdc++.h> #define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr) using namespace std; struct Node{     int ascii;     int time; }; bool cmp(Node a, Node b){     if(a.time == b.time) return a.ascii > b.ascii;     return a.time < b.time; } int main(){     fastio;     string s;     Node node[260];     while(getline(cin, s)){         for(int i = 0; i < 260; ++i){             node[i].ascii = i;             node[i].time = 0;         }         for(int i = 0; i < s.length(); ++i){             ++node[s[i]].time;         }         sort(node, node + 260, cmp);         for(int i = 0; i < 260; ++i){             if(node[i].time != 0){                 cout << node[i].ascii << " " << node[i].time << "\n";             }         }         cout << "\n";     } }
   |