Programming Challenges 习题 3.8.4

PC/UVa:110304/850

Crypt Kicker II

题目没有什么难度,只是已知明文攻击循环太长,结束条件一定要多确认几次。同时有了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
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值