洛谷:P1079
OJ:P5966
'A' 对应位移量 0,'B' 对应 1,以此类推,直到 'Z' 对应 25。'a' 到 'z' 对应 0 到 25。s[i],从其 ASCII 码中减去对应的位移量 j,得到解密后的字符。decrypted_char 小于 'A',则 decrypted_char += 26;。k:
getline(cin, k); 从标准输入读取一行,作为密钥字符串。s:
getline(cin, s); 从标准输入读取一行,作为需要解密的密文字符串。len1 = k.size();。len2 = s.size();。times = len2 / len1;。remainder = len2 % len1;。extended_key。times 次添加到 extended_key。remainder 个字符添加到 extended_key。k = extended_key;,使得密钥长度与密文长度相同。len2 个字符,k = k.substr(0, len2);。ans.resize(len2); 将结果字符串 ans 的长度调整为与密文长度相同,以便后续按索引赋值。for (int i = 0; i < len2; i++) 遍历密文的每个字符。j:
j = 0;。k[i] 在 'A' 和 'Z' 之间,j = k[i] - 'A';。k[i] 在 'a' 和 'z' 之间,j = k[i] - 'a';。j 保持为 0,即不进行位移。decrypted_char = s[i] - j;。s[i] 在 'A' 和 'Z' 之间:
decrypted_char 小于 'A',说明越过了字母表的开头,需要回绕:
decrypted_char += 26;。s[i] 在 'a' 和 'z' 之间:
decrypted_char 小于 'a',同样需要回绕:
decrypted_char += 26;。s[i] 不是字母字符,保持原样:
decrypted_char = s[i];。ans[i] = decrypted_char;。cout << ans << endl; 将解密后的明文输出到标准输出。代码实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | /**************************************************************** * Description: 2012年提高组第一题 维吉尼亚密码 * Author: Alex Li * Date: 2024-10-11 14:53:29 * LastEditTime: 2024-10-11 15:03:56 ****************************************************************/ #include <iostream> #include <string> using namespace std; int main() { string k, s, ans; getline(cin, k); // 读取整行密钥 getline(cin, s); // 读取整行密文 int len1 = k.size(); // 密钥长度 int len2 = s.size(); // 密文长度 // 将密钥扩展或截断到与密文相同的长度 if (len1 < len2) { int times = len2 / len1; int remainder = len2 % len1; string extended_key = ""; for (int i = 0; i < times; i++) extended_key += k; extended_key += k.substr(0, remainder); k = extended_key; } else { k = k.substr(0, len2); // 如果密钥比密文长,则截断 } ans.resize(len2); // 将 ans 字符串调整到正确的大小 for (int i = 0; i < len2; i++) { int j = 0; // 初始化 j if (k[i] >= 'A' && k[i] <= 'Z') j = k[i] - 'A'; else if (k[i] >= 'a' && k[i] <= 'z') j = k[i] - 'a'; // 进行解密操作 char decrypted_char = s[i] - j; // 处理大写字母的回绕 if (s[i] >= 'A' && s[i] <= 'Z') { if (decrypted_char < 'A') decrypted_char += 26; } // 处理小写字母的回绕 else if (s[i] >= 'a' && s[i] <= 'z') { if (decrypted_char < 'a') decrypted_char += 26; } else { // 如果不是字母字符,保持原样 decrypted_char = s[i]; } ans[i] = decrypted_char; // 将解密后的字符赋值给 ans 字符串 } cout << ans << endl; // 输出解密后的明文 return 0; } |