HDU 4763 Theme Section(kmp求前后缀)

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

对于每个字符串找到一个匹配的模式EAEBE,求E最大的长度是多少,A和B可以是空字符串,也可以是不相等长度的字符串

用kmp求出前面和后面相同的部分最长是多少,即fail[len],即E的长度,然后不断缩小这个长度,如果能在中间发现这个E字符串,即break

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>

using namespace std;
const int MAX = (int)1e6+10;
char str[MAX],tem[MAX];
int fail[MAX],len;
void Getfail(){
    int i=0,k = -1;
    fail[0] = -1;
    while(i < len){
        if(k == -1 || str[i] == str[k])
            fail[++i] = ++k;
        else
            k = fail[k];
    }
}
int main(void){
    int t;
    scanf("%d",&t);
    while(t--){
        scanf("%s",str);
        len = strlen(str);
        Getfail();
        int circle = fail[len];
        if(circle == 0){
            printf("0\n");
        }
        else{
            for(int i=circle;i >= 1;i--){//不断缩小E的长度
                strncpy(tem,str,i);//把前缀E这个字符串拷贝进tem
                tem[i] = '\0';
                char *p = strstr(str+i,tem);//在除去前面E的部分寻找E
                if(p == NULL)   continue;//如果没找到时
                int pos = (p - str) - 1;
                if(pos < len-i){//找到的E的位置要在最后一个E的前面
                    printf("%d\n",i);
                    break;
                }
            }
        }
    }

    return 0;
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页