c044: 10008 - What's Cryptanalysis

  1. 1. 內容
  2. 2. 範例輸入
  3. 3. 範例輸出
  4. 4. 想法
  5. 5. 程式碼

CPE 一顆星選集 49 道必考題

題目連結:https://zerojudge.tw/ShowProblem?problemid=c044

內容

給定多列文字,計算英文字母出現次數(大小寫視為相同),按照次數排序(若一樣則按照字母序)。

第一列有一個正整數 n ,代表有 n 列文字。

範例輸入

3
This is a test.
Count me 1 2 3 4 5.
Wow!!!! Is this question easy?

範例輸出

S 7
T 6
I 5
E 4
O 3
A 2
H 2
N 2
U 2
W 2
C 1
M 1
Q 1
Y 1

想法

使用 getline 一次讀取一列,遍歷判斷是否為字母。
開 struct 紀錄各個字母和出現次數,按照題目要求排序。

程式碼

C++
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
33
34
35
36
37
38
39
40
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr)
using namespace std;

struct Node{
int num;
int time;
};
bool cmp(Node a, Node b){
if(a.time == b.time) return a.num < b.num;
return a.time > b.time;
}
int main(){
fastio;
int n;
string s;
Node node[26];
for(int i = 0; i < 26; ++i){
node[i].num = i;
node[i].time = 0;
}
cin >> n;
cin.ignore();
while(n--){
getline(cin, s);
for(int i = 0; i < s.length(); ++i){
if(isalpha(s[i])){
if(isupper(s[i])){
++node[s[i] - 'A'].time;
}
else ++node[s[i] - 'a'].time;
}
}
}
sort(node, node + 26, cmp);
for(int i = 0; i < 26; ++i){
if(node[i].time == 0) break;
else cout << char(node[i].num + 'A') << " " << node[i].time << "\n";
}
}