Try   HackMD

UVa 10008 題解 — C++

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
此筆記為UVa 10008的題目詳解,包含解題思路、C++範例程式碼。

What's Cryptanalysis (ZeroJudge c044.)

題目

密碼翻譯(cryptanalysis)是指把某個人寫的密文(cryptographic writing)加以分解。這個程序通常會對密文訊息做統計分析。你的任務就是寫一個程式來對密文作簡單的分析。

輸入 / 輸出說明

輸入說明 輸出說明
Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →
Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More →

解題思路

透過 getline(cin, w) 取得輸入字串(若使用 cin >> w,在遇到空格時會結束輸入)。

我透過 code 陣列儲存每個英文字元的出現次數。若該字元為英文字元,則將字元可能出現的最大值 l 設為 l + 1(有可能全部是同個英文字元),再依序從 l ~ 1、A ~ Z 搜尋字元出現次數符合的情況,即可符合題目要求的出現次數由大到小排列字元出現次數相同,按字元的大小由小到大排列

⚠️請注意,如果你使用ZeroJudge平台的 測試執行 功能的時候,發現過不了是正常的,在正式執行時不會有問題。

⚠️請注意,如果你卡在 WA (line:1),可能是因為輸入時會跳過第一行,因此請添加 cin.ignore(); 。

範例程式碼

#include <bits/stdc++.h> using namespace std; int main () { ios::sync_with_stdio(false); cin.tie(0); int i, j; int n, a, l = 0; int code[26]={}; cin >> n; cin.ignore(); string w; for (i=0;i<n;i++) { getline(cin, w); for (j=0;j<w.size();j++) { a = -1; if (w[j] >= 'a' && w[j] <= 'z') a = w[j] - 'a'; else if (w[j] >= 'A' && w[j] <= 'Z') a = w[j] - 'A'; if (a != -1) { l++; code[a]++; } } } for (j=l;j>=1;j--) { for (i=0;i<26;i++) { if (code[i] == j) { cout << (char) (i + 'A') << " " << code[i] << endl; } } } return 0; }

運行結果

AC (3ms, 344KB)

tags: CPE 1星

查看更多資訊請至:https://www.tseng-school.com/