PC/UVa:110304/850
题目没有什么难度,只是已知明文攻击循环太长,结束条件一定要多确认几次。同时有了Crypt Kicker的经验,所以很容易AC了。
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
vector<string> vecstrPlain = { "the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog" };
void decrypt(const vector<vector<string>> &vecvecstrCipher)
{
vector<char> vcEnc, vcDec;
bool bContinue = false;
for (size_t i = 0; i < vecvecstrCipher.size(); i++)
{
const vector<string> &vecstrCipher = vecvecstrCipher[i];
if (vecstrCipher.size() == vecstrPlain.size()){
vcEnc.assign(26, '\0'), vcDec.assign(26, '\0');
bContinue = true;
//比较明文行和密文行中的每一个单词
for (size_t j = 0; j < vecstrCipher.size(); j++)
{
if (vecstrPlain[j].size() == vecstrCipher[j].size()){
for (size_t k = 0; k < vecstrPlain[j].size(); k++)
{
//如果加密表中还没有映射,或者映射相同
if (vcEnc[vecstrPlain[j][k] - 'a'] == '\0'
|| vcEnc[vecstrPlain[j][k] - 'a'] == vecstrCipher[j][k]){
vcEnc[vecstrPlain[j][k] - 'a'] = vecstrCipher[j][k];
}
else{
bContinue = false;
break;
}
//如果解密表中还没有映射,或者映射相同
if (vcDec[vecstrCipher[j][k] - 'a'] == '\0'
|| vcDec[vecstrCipher[j][k] - 'a'] == vecstrPlain[j][k]){
vcDec[vecstrCipher[j][k] - 'a'] = vecstrPlain[j][k];
}
else{
bContinue = false;
break;
}
}
//如果该单词解密成功,bContinue为true,否则为false
//false情况结束当前行的解密,尝试下一行
if (!bContinue) break;
}
else{
bContinue = false;
break;
}
}
//如果该行解密成功,bContinue为true,否则为false
//true情况结束已知明文攻击
if (bContinue) break;
}
}
if (!bContinue){
cout << "No solution." << endl;
return;
}
for (size_t i = 0; i < vecvecstrCipher.size(); i++)
{
const vector<string> &vecstrCipher = vecvecstrCipher[i];
for (size_t i = 0; i < vecstrCipher.size() - 1; i++)
{
for (const char &ch : vecstrCipher[i])
{
cout << vcDec[ch - 'a'];
}
cout << ' ';
}
for (const char &ch : vecstrCipher.back())
{
cout << vcDec[ch - 'a'];
}
cout << endl;
}
}
int main()
{
int T = 0;
cin >> T;
cin.get();
cin.get();
for (int t = 0; t < T; t++)
{
vector<vector<string>> vecvecstrCipher;
string strLine;
while (getline(cin, strLine)){
if (strLine.empty()) break;
istringstream iss(strLine);
string strWord;
vector<string> vecstrWord;
while (iss >> strWord){
vecstrWord.push_back(strWord);
}
vecvecstrCipher.push_back(vecstrWord);
}
decrypt(vecvecstrCipher);
if (t != T - 1) cout << endl;
}
return 0;
}
/*
1
vtz ud xnm xugm itr pyy jttk gmv xt otgm xt xnm puk ti xnm fprxq
xnm ceuob lrtzv ita hegfd tsmr xnm ypwq ktj
frtjrpgguvj otvxmdxd prm iev prmvx xnmq
*/