Problem I : What's Cryptanalysis?
Description
Cryptanalysis is the process of breaking someone else'scryptographic writing. This sometimes involves some kind of statisticalanalysis of a passage of (encrypted) text. Your task is to write a programwhich performs a simple analysis of a given text.input
The first line of input contains a single positivedecimal integern. This is the number of lines which follow in theinput. The next n lines will contain zero or more characters (possiblyincluding whitespace). This is the text which must be analyzed.
output
Each line of output contains a single uppercase letter,followed by a single space, then followed by a positive decimal integer. Theinteger indicates how many times the corresponding letter appears in the inputtext. Upper and lower case letters in the input are to be considered the same.No other characters must be counted. The output must be sorted in descendingcount order; that is, the most frequent letter is on the first output line, andthe last line of output indicates the least frequent letter. If two lettershave the same frequency, then the letter which comes first in the alphabet mustappear first in the output. If a letter does not appear in the text, then thatletter must not appear in the output.
sample input
3
This is a test.
Count me 1 2 3 4 5.
Wow!!!! Is thisquestion easy?
sample output
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
题意: 按照出现次数从大到小排列,次数相同的,按照字典中的字母顺序排列。
解题思路: 利用struct和排序。
代码:
<span style="font-style: normal;">#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
usingnamespace std;
constint maxN=40;
structnode{
char ch;
int cnt;
}a[maxN];
bool cmp(node a,node b){
if(a.cnt!=b.cnt){
return a.cnt>b.cnt;
}
else{
return a.ch<b.ch;
}
}
void initial(){
for(int i=0;i<26;i++){
a[i].ch ='A'+i;
a[i].cnt=0;
}
}
void solve(){
int n;
scanf("%d\n",&n);
while(n-->0){
string str;
getline(cin,str);
for(int i=0;i<str.length();i++){
if(str[i]<='z'&&str[i]>='a'){
a[str[i]-'a'].cnt++;
}
else if(str[i]<='Z'&&str[i]>='A'){
a[str[i]-'A'].cnt++;
}
}
}
sort(a,a+26,cmp);
for(int i=0;i<26;i++){
if(a[i].cnt>0){
printf("%c%d\n",a[i].ch,a[i].cnt);
}
}
}
int main(){
initial();
solve();
return 0;
}</span>