---
# System prepended metadata

title: What's Cryptanalysis?(UVA10008)
tags: [CPE一顆星必考題, CPE 一顆星]

---

# What's Cryptanalysis?(UVA10008)
## [程式繳交區](https://hackmd.io/@Renektonn/rynx3T6v1l/edit)
## 題目
[點我](https://onlinejudge.org/external/100/10008.pdf)

## 解題網站
[UVA](https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=12&page=show_problem&problem=949)
[ZJ](https://zerojudge.tw/ShowProblem?problemid=c044)

## Hint
字母統計、排序

## 演算法
```
1. 輸入n
2. 重複n次
2.1 輸入一行進str
2.2 統計字母出現次數arr，大小寫視為相同，英文字母以外的字元不列入計算
3. 對arr進行排序，由大到小，若相同，則ASCII code較小的在前
4. 輸出答案
```

## 1/21講到這

```cpp=
#include <bits/stdc++.h>
#define int long long int
using namespace std;


signed main(){	
    pair <char, int> arr[26];
    for (int i = 0; i < 26; i++) {
        arr[i].first = 'A' + i;
        arr[i].second = 0;
    }
    int n;
    cin >> n;
    string str;
    getline(cin, str);
    while (n--) {
        getline(cin, str);
        for (int i = 0; i < str.size(); i++) {
            char c = str[i];
            int idx;
            if ('A' <= c and c <= 'Z') {
                idx = c - 'A';	
                arr[idx].second++;
            } else if ('a' <= c and c <= 'z') {
                idx = c - 'a';
                arr[idx].second++;
            }	
        }
    }
    return 0;
}

```

## 程式碼
```cpp=
#include <bits/stdc++.h>
using namespace std;

int cmp (pair <char, int> a, pair <char, int> b) {
    if (a.second != b.second) {
        return a.second > b.second;
    } else {
        return a.first < b.first;
    }
}

int main() {
    vector <pair <char, int>> v(26);
    for (int i = 0; i < 26; i++) {
        v[i].first = 'A' + i;
        v[i].second = 0;
    }
    int n;
    cin >> n;
    cin.ignore();
    while (n--) {
        string str;
        getline(cin, str);
        for (int i = 0; i < str.size(); i++) {
            char c = str[i];
            int idx;
            if ('A' <= c and c <= 'Z') {
                idx = c - 'A';
                v[idx].second++;
            } else if ('a' <= c and c <= 'z') {
                idx = c - 'a';
                v[idx].second++;
            }
        }
    }
    sort(begin(v), end(v), cmp);
    for (int i = 0; i < 26; i++) {
        if (v[i].second == 0) {
            break;
        }
        cout << v[i].first << " " << v[i].second << endl;
    }

    return 0;
}

```

