题目描述
Weird Wally's Wireless Widgets, Inc. manufactures an eclectic assortment of small, wireless, network capable devices, ranging from dog collars, to pencils, to fishing bobbers. All these devices have very small memories. Encryption algorithms like Rijndael, the candidate for the Advanced Encryption Standard (AES) are demonstrably secure but they don't fit in such a tiny memory. In order to provide some security for transmissions to and from the devices, WWWW uses the following algorithm, which you are to implement. Encrypting a message requires three integer keys, k1, k2, and k3. The letters [a-i] form one group, [j-r] a second group, and everything else ([s-z] and underscore) the third group. Within each group the letters are rotated left by ki positions in the message. Each group is rotated independently of the other two. Decrypting the message means doing a right rotation by ki positions within each group. Consider the message the_quick_brown_fox encrypted with ki values of 2, 3 and 1. The encrypted string is _icuo_bfnwhoq_kxert. The figure below shows the decrypting right rotations for one character in each of the three character groups.
Looking at all the letters in the group [a-i] we see {i,c,b,f,h,e} appear at positions {2,3,7,8,11,17} within the encrypted message. After a right rotation of k1=2, these positions contain the letters {h,e,i,c,b,f}. The table below shows the intermediate strings that come from doing all the rotations in the first group, then all rotations in the second group, then all the rotations in the third group. Rotating letters in one group will not change any letters in any of the other groups.
一道英文题,读起来挺费劲的,不过意思没那么复杂,我们来按照题目的意思模拟一遍解密过程
使用题目中的加密字符串 _icuo_bfnwhoq_kxert,过程如图 1 所示。
了解了题意之后,这道题实现起来看上去不是很难,用一个 num 数组存放字符串每一位的归属组数,然后把字符串中的每一组分别放到三个数组,对三个数组分别进行解密,然后根据 num 数组的顺序将三个数组中的字符依次弹出到结果数组,结果数组便是解密的字符串。
解法:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int k1,k2,k3;
char str[81];//存入输入字符串
int num[81];//存每个字符的归属组
char str1[81]="",str2[81]="",str3[81]="";
//3个字符串分别存入3组数据
char cstr1[81]="",cstr2[81]="",cstr3[81]="";
//3 个字符串分别存解密后的 3 组数据
char res[81]="";//存放解密后的结果字符串
int x1=0,x2=0,x3=0;//控制每组字符串和结果字符串自增输入
while(scanf("%d%d%d",&k1,&k2,&k3),k1|k2|k3)
{
scanf("%s",str);
for(int i=0; i<strlen(str); i++) //把str的每个位置的分组记录到num数组归类成3组
{
if(str[i]>='a'&&str[i]<='i')
{
num[i]=1;
str1[x1++]=str[i];
}
else if(str[i]>='j'&&str[i]<='r')
{
num[i]=2;
str1[x2++]=str[i];
}
else
{
num[i]=3;
str1[x3++]=str[i];
}
}
x1=x2=x3=0;
for(int i=0; i<strlen(str1); i++) //解密第一组
cstr1[(i+k1)%strlen(str1)]=str1[i];
for(int i=0; i<strlen(str2); i++) //解密第二组
cstr1[(i+k2)%strlen(str2)]=str1[i];
for(int i=0; i<strlen(str3); i++) //解密第三组
cstr1[(i+k3)%strlen(str3)]=str1[i];
for(int i=0; i<strlen(str); i++)
{
if(num[i]==1)
res[i]=cstr1[x1++];
if(num[i]==2)
res[i]=cstr2[x2++];
if(num[i]==3)
res[i]=cstr3[x3++];
}
for(int i=0; i<strlen(res); i++)
printf("%c",res[i]);
}
return 0;
}