Theme Section
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5100 Accepted Submission(s): 2556
Problem 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?
Input
The integer N in the first line denotes the total number of songs in the festival. Each of the following N lines consists of one string, indicating the notes of the i-th (1 <= i <= N) song. The length of the string will not exceed 10^6.
Output
There will be N lines in the output, where the i-th line denotes the maximum possible length of the theme section of the i-th song.
Sample Input
5
xy
abc
aaa
aaaaba
aaxoaaaaa
Sample Output
0
0
1
1
2
Source
2013 ACM/ICPC Asia Regional Changchun Online
问题描述:求S的最长公共前缀后缀E,且要满足S由EAEBE构成,其中A和B也是S的子串,或者为空。
解题思路:先求出S的最长公共前缀后缀,然后截取中间串,查询公共串是否是中间串的子串即可。具体看程序
AC的C++程序:
#include<iostream>
#include<cstring>
using namespace std;
const int N=1000010;
char p[N],s[N],sub[N];
int Next[N],Next2[N];
void GetNext(char p[],int next[])
{
next[0]=-1;
int k=-1,j=0,plen=strlen(p);
while(j<plen)
{
if(k==-1||p[k]==p[j])
{
k++,j++;
next[j]=k;
}
else
k=next[k];
}
}
int KMP(char s[],char p[],int next[])
{
int i=0,j=0,slen=strlen(s),plen=strlen(p);
while(i<slen&&j<plen)
{
if(j==-1||s[i]==p[j])
i++,j++;
else
j=next[j];
}
if(j==plen)
return 1;
else
return 0;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",p);
GetNext(p,Next);
int len=strlen(p);
int l=Next[len];
if(l<=0)
printf("0\n");
else{
bool flag=false;
while(3*l>len) l=Next[l];
while(l>0){
strncpy(s,p+l,(len-2*l));//截取中间串s
s[len-2*l]='\0';
strncpy(sub,p,l);//截取公共前缀后缀sub
sub[l]='\0';
//查找s中是否含有sub
GetNext(sub,Next2);
if(KMP(s,sub,Next2)==1)
{
flag=true;
break;
}
l=Next[l]; //寻找更小的
}
printf("%d\n",flag?l:0);
}
}
return 0;
}