Y - Theme Section HDU - 4763(kmp net值的运用)

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

题意:给定一个字符串S,要求你找到一个最长的子串,它既是S的前缀,也是S的后缀,并且在S的内部也出现过(非端点)

#include <iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<queue>
#include<algorithm>
#define ll long long
using namespace std;
const int inf=0x3f3f3f3f;
char a[1000005];
int n,m;
int net[1000005];
void tao()//计算net值
{
    int i=0;
    int j=-1;
    net[0]=-1;
    while(i<m)
    {
        if(j==-1||a[i]==a[j])
        {
            net[++i]=++j;
        }
        else
            j=net[j];
    }
}
int kmp()
{
    for(int i=net[m]; ~i; i=net[i])
    {//next[len]=i,在[2 * i ,len - i](因为不能重合)
        //不存在的话令i=next[i],而不是i--,继续找
        for(int j=i*2; j<=m-i; j++)
        {
            if(net[j]==i)//找是否有next[j]=i
                return i;//存在则i就为答案
        }

    }
    return 0;
}
int main()
{
    scanf("%d",&n);
    for(int i=0; i<n; i++)
    {
        scanf("%s",a);
        m=strlen(a);
        if(m<3)//小于三直接舍弃
            printf("0\n");
        else
        {
            tao();
            printf("%d\n",kmp());
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Kuguotao/article/details/89012711