1. 程式人生 > >UVA10008 What's Cryptanalysis?【字元統計+sort】

UVA10008 What's Cryptanalysis?【字元統計+sort】

Cryptanalysis is the process of breaking someone else’s cryptographic writing. This sometimes involvessome kind of statistical analysis of a passage of (encrypted) text. Your task is to write a program whichperforms a simple analysis of a given text.

Input

The first line of input contains a single positive decimal integer n. This is the number of lines whichfollow in the input. The next n lines will contain zero or more characters (possibly including 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 apositive decimal integer. The integer indicates how many times the corresponding letter appears inthe input text. Upper and lower case letters in the input are to be considered the same. No othercharacters must be counted. The output must be sorted in descending count order; that is, the mostfrequent letter is on the first output line, and the last line of output indicates the least frequent letter.If two letters have the same frequency, then the letter which comes first in the alphabet must appearfirst in the output. If a letter does not appear in the text, then that letter must not appear in theoutput.

Sample Input

3

This is a test.

Count me 1 2 3 4 5.

Wow!!!! Is this question 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

問題簡述:(略)

問題分析:這是一個字元統計問題,需要排序後輸出結果。

程式說明:(略)

題記:(略)

參考連結:(略)

AC的C語言程式如下:

/* UVA10008 What's Cryptanalysis? */

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <ctype.h>

using namespace std;

typedef struct {
    char letter;
    int count;
} _node;

const int N = 26;
_node lcount[N];

void init()
{
    for(int i=0; i<N; i++) {
        lcount[i].letter = 'A' + i;
        lcount[i].count = 0;
    }
}

int cmp(_node a, _node b)
{
    return a.count != b.count ? a.count > b.count : a.letter < b.letter;
}

int main()
{
    int n;
    string s;

    while(~scanf("%d", &n)) {
        getchar();

        init();

        while(n--) {
            getline(cin, s);

            for(int i=0; s[i]; i++)
                if(isalpha(s[i]))
                    lcount[toupper(s[i]) - 'A'].count++;
        }

        sort(lcount, lcount + N, cmp);

        for(int i=0; i<N && lcount[i].count; i++)
            printf("%c %d\n", lcount[i].letter, lcount[i].count);
    }

    return 0;
}