HDU-4763 Theme Section KMP

时间:2023-03-09 07:44:48
HDU-4763   Theme Section  KMP

题意:求最长的子串E,使母串满足EAEBE的形式,A、B可以任意,并且不能重叠。

题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid=4763

思路:这题对next数组可以说是考察的非常的细,也是通过这道题,也让我对next数组有了更深刻的了解。或者说之前只是云里雾里。(题外话就到这)。首先我们求出该字符串的Next数组,我们都知道对于Next[i]是从串首开始长度为i的子串的前缀与后缀相同的最大长度。那么我们标记字符串的中间位置,就是已该位置结束的字符串他的前缀与母串的后缀有相同部分,然后我们枚举以2-n-1为字符串末尾,来找第一个E。然后不断的找出最大值。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e6+;
char s[maxn];
int Next[maxn];
int vis[maxn];
int len;
void get_next()
{
int i=;
int j=-;
Next[]=-;
while(i<len)
{
if(s[i]==s[j]||j==-)
Next[++i]=++j;
else
j=Next[j];
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
len=strlen(s);
get_next();
memset(vis,,sizeof(vis));
int x=len;
while(x>)
{
if(len>=*x)
vis[x]=;
x=Next[x];
}
int maxx=;
for(int i=len-;i>;i--)
{
x=i;
while(x>)
{
if(vis[x]&&i>=*x&&len>=i+x)
{
maxx=max(maxx,x);
break;
}
x=Next[x];
}
}
printf("%d\n",maxx);
}
return ;
}