据说是恺撒大帝最早使用凯撒加密这种方法传递军情。恺撒加密是一种替代加密方法,根据字母表将明文中的每个字母移动常量位k(密钥),末尾字母则回卷到字母表开头。例如,假设k等于3,则a会被替换D,b会被替换成E,x会被替换为A(这里密文大写)。
例如:明文是"Attack in the morning",密钥k等于3,则密文是"DWWDFN LQ WKH PRUQLQJ"。
可以用英文字母的频率统计法对凯撒加密进行破解,即英文字母的使用频率是一定规律的,从中我们可以发现字母’E’的使用是最高的。
输入的密文有多行(不超过20行),每行不超过80个字符。密文的输入是’#‘为结束标志,即最后一行是一个’#'。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> vs;
int get_key()
{
int fre[26] = {0};
for(string& s: vs)for(char ch:s)if(isalpha(ch))fre[ch-'A']++;
int idx = 0;
for(int i=1;i<26;i++)if(fre[i]>fre[idx])idx=i;
int key = (idx - ('E' - 'A') + 26) % 26;
return key;
}
int main()
{
string s;
while(getline(cin, s))
{
vs.push_back(s);
if(s=="#")break;
}
int key = get_key();
for(string& s: vs)
{
for(char ch:s)
cout<<(isalpha(ch) ? char((ch - 'A' - key + 26) % 26 + 'A') : ch);
cout<<endl;
}
return 0;
}