# [HDU4763]Theme Section（KMP）

### Description

It's time for music! A lot of popular musicians are invited to join us in the music festival. Each of them will play one of their representative songs. To make the programs more interesting and challenging, the hosts are going to add some constraints to the rhythm of the songs, i.e., each song is required to have a 'theme section'. The theme section shall be played at the beginning, the middle, and the end of each song. More specifically, given a theme section E, the song will be in the format of 'EAEBE', where section A and section B could have arbitrary number of notes. Note that there are 26 types of notes, denoted by lower case letters 'a' - 'z'.
To get well prepared for the festival, the hosts want to know the maximum possible length of the theme section of each song. Can you help us?

HDU

KMP

## 代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;

#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))

const int maxN=1001000;
const int inf=2147483647;

int n;
char str[maxN];
int Next[maxN];
bool GoLast[maxN];

int main()
{
ios::sync_with_stdio(false);
int T;cin>>T;
while (T--)
{
mem(GoLast,0);
cin>>(str+1);n=strlen(str+1);
Next[0]=-1;Next[1]=0;
for (int i=2;i<=n;i++)//求Next
{
int j=Next[i-1];
while ((j!=0)&&(str[j+1]!=str[i])) j=Next[j];
if (str[j+1]==str[i]) Next[i]=j+1;
else Next[i]=0;
}
int Ans=0;
for (int i=n;i!=0;i=Next[i]) if (i+i<=n) GoLast[i]=1;//给能与结尾匹配上的前缀打上标记
for (int i=n-1;i>=1;i--)
{
int now=i;
while (now)//寻找合法前缀
{
if ((GoLast[now])&&(now+now<=i)&&(now+i<=n)){
Ans=max(Ans,now);break;//更新最大值
}
now=Next[now];
}
}
printf("%d\n",Ans);
}
return 0;
}


HNCJ OIer