E - Theme Section
时限:1000MS 内存:32768KB 64位IO格式:%I64d & %I64u
问题描述
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?
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?
输入
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.
输出
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.
样例输入
5 xy abc aaa aaaaba aaxoaaaaa
样例输出
0 0 1 1 2
分析:寻求前、中、后连续的字串相等的最大长度。
思路:曾经做过,KMP算法。
CODE:
#include <iostream>
#include <cstdio>
#include <string.h>
#include <cmath>
#define rep(i,a,n) for(int i=a;i<n;i++)
using namespace std;
const int maxn=1000005;
int nxt[maxn];
void GetNext(char c[])
{
int Len=strlen(c);
nxt[0]=-1;
int k=-1,i=0;
while(i<Len)
{
if(k==-1||c[i]==c[k]){
k++,i++;
nxt[i]=k;
}
else
k=nxt[k];
}
return ;
}
void ValGetNext(char c[])
{
int Len=strlen(c);
nxt[0]=-1;
int k=-1,i=0;
while(i<Len-1)
{
if(k==-1 ||c[i]==c[k]){
k++,i++;
if(c[i]!=c[k])
nxt[i]=k;
else
nxt[i]=nxt[k];
}
else
k=nxt[k];
}
return ;
}
int kmp(char c1[],char c2[])
{
int len1=strlen(c1),len2=strlen(c2);
int i=1,j=0;
while(i<len1-1&&j<len2)
{
if(j==-1||c1[i]==c2[j])
i++,j++;
else
j=nxt[j];
}
if(j==len2)
return i-j+1;
return -1;
}
int main()
{
ios::sync_with_stdio(false);
int t; cin>>t;
char c[maxn];
while(t--){
cin>>c;
int len=strlen(c);
if(len==3){
if(c[0]==c[1]&&c[0]==c[2])
cout<<1<<endl;
else
cout<<0<<endl;
continue;
}
bool flag=false;
GetNext(c);
// for(int i=0;i<=len;i++)
// cout<<nxt[i]<<' ';
// cout<<endl;
int ans=nxt[len];
// if(ans==len-1){
// rep(i,0,len-2)
// cout<<c[i];
// cout<<endl;
// continue;
// }
// cout<<ans<<endl;
while(ans){
rep(i,1,len-1){
if(nxt[i]==ans){
// cout<<ans<<endl;
flag=true;
break;
}
// if(flag)
// break;
// ans=nxt[ans];
// cout<<flag<<endl;
}
if(flag)
break;
ans=nxt[ans];
}
cout<<ans<<endl;
}
return 0;
}