## UVA 10008 - What's Cryptanalysis? ### 題意: ###### 計算 l (這是line的簡寫,不是數字1) 行句子裡面的字母數量,由多到少排列,如果出現次數相同,則照字母排列 (alphabetical order)。 ### 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 ``` ### 程式碼: ```cpp= #include <iostream> #include <map> #include <string> #define haku author using namespace std; int main() { int l, max = 0; string str; map<char, int> mp; // 我想不到怎麼命名了XD getline(cin, str); l = stoi(str); while(l--) { getline(cin, str); for(int i = 0; i < str.size(); i++) { // 感覺這裡可以更簡潔,之後再來看看 if (str[i] >= 'a' && str[i] <= 'z'){ char tmp = str[i] - 'a' + 'A'; if (mp.find(tmp) != mp.end()) mp[tmp]++; else mp.insert({tmp, 1}); if (mp[tmp] > max) max = mp[tmp]; } else if (str[i] >= 'A' && str[i] <= 'Z') { if (mp.find(str[i]) != mp.end()) mp[str[i]]++; else mp.insert({str[i], 1}); if (mp[str[i]] > max) max = mp[str[i]]; } } } while(max) { for(auto& p: mp) { if (p.second == max) cout << p.first << ' ' << p.second << endl; } max--; } return 0; } ``` #### 更新: ###### 找到更簡潔的寫法了,但要記個東西 ###### <cctype> 裡面的 toupper() (轉大寫) 和 isalpha() (判斷是否為英文字母) 另外可以多記一個 tolower(),也蠻常用到的。 ```cpp= #include <iostream> #include <map> #include <string> #include <cctype> // for isalpha() & tolower() #include <vector> #include <algorithm> #define haku author using namespace std; bool cmp(pair<char, int> a, pair<char, int> b) { if (a.second != b.second) return a.second > b.second; return a.first < b.first; } int main() { int l, max = 0; string str; map<char, int> mp; // 我想不到怎麼命名了XD getline(cin, str); l = stoi(str); while (l--) { getline(cin, str); for (int i = 0; i < str.size(); i++) { if (isalpha(str[i])) { char tmp = toupper(str[i]); if (mp.find(tmp) != mp.end()) mp[tmp]++; else mp.insert({ tmp, 1 }); if (max < mp[tmp]) max = mp[tmp]; // 紀錄最大值是多少 } } } vector<pair<char, int>> v(mp.begin(), mp.end()); sort(v.begin(), v.end(), cmp); for (auto& p : v) { cout << p.first << ' ' << p.second << endl; } return 0; } ```