Clairewd’s message HDU - 4300
题目链接:https://cn.vjudge.net/contest/163024#problem/L
题目大意:给你一个二十六位的密码表A,然后给你一段文字S。前面部分完整的是密文,后面是未必完整的明文,让你输出完整的密文+完整的明文。
要求使得文字S最短
题目分析:
其实就是求第二个字符串的前缀和后缀的匹配,密文是全部的,但是明文可能有,也可能没有。所以拿第二个字符串的前一半去匹配后一半即可。
input:
2
abcdefghijklmnopqrstuvwxyz
abcdab
qwertyuiopasdfghjklzxcvbnm
qwertabcde
output:
abcdabcd
qwertabcde
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
int Next[maxn], len;
char Transform[30], str[maxn];
void get_next()
{
int i, j;
Next[0] = 0;
for(i = 1; i < len; i++)
{
j = Next[i - 1];
while(j > 0 && str[i] != str[j])
j = Next[j - 1];
if(str[i] == str[j])
Next[i] = j + 1;
else
Next[i] = 0;
}
}
int kmp()
{
get_next();
int j = 0, i;
for(i = (len + 1) / 2; i < len; i++)
{
while(j > 0 && Transform[str[i] - 'a'] != str[j])
j = Next[j - 1];
if(Transform[str[i] - 'a'] == str[j])
j++;
}
return j;
}
int main()
{
int t, i;
scanf("%d", &t);
while(t--)
{
scanf("%s %s", Transform, str);
len = strlen(str);
int cnt = len;
int ans = kmp();
for(i = ans; i < len - ans; i++)
str[cnt++] = strchr(Transform, str[i]) - Transform + 'a';
str[cnt] = '\0';
//strchr是计算机的一个函数,原型为extern char *strchr(const char *s,char c),可以查找字符串s中首次出现字符c的位置。
printf("%s\n", str);
}
}