题目:
史上最难读懂的题目。
给一个字符串,由密文+明文两部分组成,明文就是密文的翻译。密文是完整的,但是明文不一定完整,也可能没有明文。给出明文到密文的字母对应。输出密文+完整的明文。若有多种情况使得总长最短。
分析:
原字符串 s 是 密+明,将它按照翻译方式全翻译完后得到 乱+密,我们将得到的字符串称为 t 。我们只需要 t 的后缀和 s 的前缀的最大匹配即可得到完整的密文部分,再由那个翻译表,就可反推出密文对应的明文,连起来输出即可。
若原字符串长度为 n ,那么密文最短是 n/2,最长是n。为了使总长最短,那我们让密文部分尽可能短明文部分尽可能长即可。由长到短遍历检测明文部分,一旦匹配上就退出。
代码:
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <set>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
#define ms(a,b) memset(a,b,sizeof(a))
typedef long long ll;
typedef unsigned long long ull;
const int MAXN=1e5+5;
const double EPS=1e-8;
const int INF=0x3f3f3f3f;
const int base = 163;
char to[MAXN],s[MAXN];
ull Hash1[MAXN],Hash2[MAXN],p[MAXN];
int n,pos[30];
void Hash(){
Hash1[0] = Hash2[0] = 0;
for(int i=1;i<=n;i++){
Hash1[i] = Hash1[i-1] * base + (s[i] - 'a');
Hash2[i] = Hash2[i-1] * base + (to[s[i] - 'a'] - 'a');
}
}
ull getHash(int l,int r,ull g[]){
return g[r] - g[l-1] * p[r-l+1];
}
int main(){
int T;
scanf("%d",&T);
p[0] = 1;
for(int i=1;i<=MAXN;i++){
p[i] = p[i-1] * base;
}
while(T--){
scanf("%s",to);
scanf("%s",s+1);
for(int i=0;i<26;i++){
pos[to[i] - 'a'] = i;
}
n = strlen(s+1);
Hash();
int ans=0;
for(int i=n/2;i>=1;i--){
ull t1 = getHash(1,i,Hash1);
ull t2 = getHash(n-i+1,n,Hash2);
if(t1 == t2){
ans = i;
break;
}
}
for(int i=1;i<=n-ans;i++){
printf("%c",s[i]);
}
for(int i=1;i<=n-ans;i++){
printf("%c",pos[s[i] - 'a'] + 'a');
}
puts("");
}
return 0;
}