Theme Section
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2623 Accepted Submission(s): 1197
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?
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
这个题困扰了好久,后来发现其实就是在字符串中找一个最长子串使其既是前后缀,还在串中出现过且不能重叠。搞完next数组以后从最后一位还是,将每一位失配的位置标记好。然后判断是否中间存在就可以了,注意不能重叠,所以相当于把整个串切成三段,根据next性质找一下最大的就可以了,想了好久=w=。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define mem(a) memset((a),0,sizeof(a))
using namespace std;
char s[1000000+10];
int ntr[1000000+10];
bool vis[1000000+10];
void get_ntr(char *s)
{
int i=0,j=-1;
ntr[i]=-1;
int len=strlen(s);
while(i<=len)
{
if(j==-1||s[i]==s[j])
{
i++;
j++;
ntr[i]=j;
}
else
j=ntr[j];
}
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
scanf("%s",s);
int len=strlen(s);
get_ntr(s);
mem(vis);
int k=len;
while(k>0)
{
if(k*2<=len) vis[k]=1;
k=ntr[k];
}
int ans=0;
for(int i=len-1;i>=0;i--)
{
k=i;
while(k>0)
{
if(vis[k]==1&&2*k<=i&&i+k<=len)
{
ans=max(ans,k);
break;
}
k=ntr[k];
}
}
printf("%d\n",ans);
}
return 0;
}