HDU 4300 Clairewd’s message(KMP)
Clairewd’s message
Clairewd is a member of FBI. After several years concealing in BUPT, she intercepted some important messages and she was preparing for sending it to ykwd. They had agreed that each letter of these messages would be transfered to another one according to a conversion table. Unfortunately, GFW(someone's name, not what you just think about) has detected their action. He also got their conversion table by some unknown methods before. Clairewd was so clever and vigilant that when she realized that somebody was monitoring their action, she just stopped transmitting messages. But GFW knows that Clairewd would always firstly send the ciphertext and then plaintext(Note that they won't overlap each other). But he doesn't know how to separate the text because he has no idea about the whole message. However, he thinks that recovering the shortest possible text is not a hard task for you. Now GFW will give you the intercepted text and the conversion table. You should help him work out this problem.
Input
Output
Sample Input
Sample Output
#include<cstdio> #include<cstring> #include<string> #include<algorithm> #include<set> #include<map> #include<queue> #include<vector> #include<iterator> #include<utility> #include<sstream> #include<iostream> #include<cmath> #include<stack> using namespace std; const int INF=1000000007; const double eps=0.00000001; int pi[200005]; void GetPi(const string& sub) //KMP得到len长度字符串的最大后缀长度pi[len-1](从0到len-1,所以len对应pi[len-1]) { memset(pi,0,sizeof(pi)); int len=sub.length(); int be=1,match=0; while(be+match<len) { if(sub[be+match]==sub[match]) { match++; pi[be+match-1]=match; } else { if(match==0) be++; else { be+=match-pi[match-1]; match=pi[match-1]; } } } } map<char,char> change,rev; //翻译表和逆向翻译表 int main() { int T; cin>>T; while(T--) { string table,S; change.clear(),rev.clear(); cin>>table>>S; for(int i=0;i<26;i++) change[i+'a']=table[i],rev[table[i]]=i+'a'; //保存下来 string another=S; int len=S.length(); for(int i=0;i<len;i++) another[i]=change[S[i]]; GetPi(S+another); //KMP一下 int ans=pi[2*len-1]; while(ans>0&&ans*2>len) ans=pi[ans-1]; //找到最接近len/2的最大后缀长度 string res=S.substr(0,len-ans); //只截取密文部分 string t=res; for(int i=0;i<res.length();i++) t[i]=rev[res[i]]; //逆向翻译 cout<<res+t<<endl; } return 0; }

浙公网安备 33010602011771号