UVa Problem 850 Crypt Kicker II (解密 II)

// Crypt Kicker II (解密 II) // PC/UVa IDs: 110304/850, Popularity: A, Success rate: average Level: 2 // Verdict: Accepted // Submission Date: 2011-05-23 // UVa Run Time: 0.016s // // 版权所有(C)2011,邱秋。metaphysis # yeah dot net #include <iostream> #include <vector> #include <sstream> #include <iterator> using namespace std; void decipher(vector < string > & plain, vector < vector < string > > & encrypted) { string cipher(26, '*'); for (vector < vector < string > >::iterator t = encrypted.begin(); t != encrypted.end(); t++) // 密文单词数量和明文单词数量相等才继续比较。 if ((*t).size() == plain.size()) { // 密文各单词长度与明文各单词长度相同才继续予以比较。 vector < string >::iterator a = (*t).begin(); vector < string >::iterator b = plain.begin(); for (; a != (*t).end() && (*a).length() == (*b).length(); a++, b++) ; // 各单词长度相同,尝试匹配。 if (a == (*t).end()) { // 保存当前密码,以便不能匹配时恢复。 string tmp = cipher; bool matched = true; for (a = (*t).begin(), b = plain.begin(); a != (*t).end(); a++, b++) { string e = *a; string p = *b; for (int i = 0; i < e.length(); i++) // 若当前密文字母无对应明文文字母匹配, // 则将密文字母与明文字母匹配。 if (cipher[e[i] - 'a'] == '*') { cipher[e[i] - 'a'] = p[i]; } else { // 若已有明文字母与该密文字母 // 相匹配,则检查需要 // 匹配的密文是否与当前相同, // 若不同,则表示有冲突。 if (cipher[e[i] - 'a'] != p[i]) { matched = false; break; } } if (!matched) break; } // 满足所有匹配,按当前cipher输出密文,否则还原密码为初始状态。 if (matched) { for (vector < vector < string > >::iterator t = encrypted.begin(); t != encrypted.end(); t++) { for (vector < string >::iterator v = (*t).begin(); v != (*t).end(); v++) { string tmp = (*v); for (int j = 0; j < tmp.length(); j++) cout << cipher[tmp[j] - 'a']; if (v < (*t).end() - 1) cout << " "; } cout << endl; } return; } else cipher = tmp; } } // 无解。 cout << "No solution." << endl; } int main(int ac, char *av[]) { vector < vector < string > > encrypted; // 保存密文。 vector < string > plain; // 已知明文。 string word, line; // 当前单词,当前行。 int cases; // 测试数据组数。 int current = 0; // 当前数据组数。 // 将明文拆分成单词。 istringstream iss("the quick brown fox jumps over the lazy dog"); while (iss >> word) plain.push_back(word); // 读入数据组数。 cin >> cases; cin.ignore(); // 忽略空行。 getline(cin, line); while (current < cases) { encrypted.clear(); // 读入密文,并拆分成单词。 while (getline(cin, line), line.length() > 0) { // 必须将输入字符串流的标志清空才能进行新的输入。 iss.clear(); iss.str(line); vector < string > tmp; while (iss >> word) tmp.push_back(word); encrypted.push_back(tmp); } // 解码。 decipher(plain, encrypted); current++; if (current < cases) cout << '\n'; } return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值