a730簡單位置對應的替換密碼
CPE:Substitution Cypher (UVa 865)
依字母表建立字元映射,保留未列入的字元。
解題思路
明文字母表第 i 個字元對應替換字母表第 i 個字元,因此先建立一對一的查表關係。掃描每個待轉換文字字元時,只查原字元一次,不能把剛替換的結果再送入映射,否則會造成連鎖替換。
每組先反過來印出替換字母表、明文字母表,再印轉換文字。逐行讀取以保留空白和標點,空白行是測試組分界,EOF 也可結束最後一組。未出現在明文字母表的大小寫字母、數字及符號均原樣保留,組與組之間印一空行。
Step-by-step animation
示意:abc → xyz,文字 aB c
步驟 1 / 3
建立表
只替換 a、b、c。
a→x
b→y
c→z
- 映射數
- 3
#include <iostream>
#include <string>
using namespace std;
int main() {
int t;
cin >> t;
string line;
getline(cin, line);
for (int cs = 0; cs < t; ++cs) {
string plain, cipher;
do {
if (!getline(cin, plain))
return 0;
if (!plain.empty() && plain.back() == '\r')
plain.pop_back();
} while (plain.empty());
getline(cin, cipher);
if (!cipher.empty() && cipher.back() == '\r')
cipher.pop_back();
char table[256];
for (int i = 0; i < 256; ++i)
table[i] = char(i);
for (size_t i = 0; i < plain.size(); ++i)
table[(unsigned char)plain[i]] = cipher[i];
if (cs)
cout << '\n';
cout << cipher << '\n' << plain << '\n';
while (getline(cin, line)) {
if (!line.empty() && line.back() == '\r')
line.pop_back();
if (line.empty())
break;
for (unsigned char c : line)
cout << table[c];
cout << '\n';
}
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。