HDU 4763 Theme Section

题目:http://acm.hdu.edu.cn/showproblem.php?pid=4763

题意:给定一个字符串,找出能构成"EAEBE"形式的字符串的E的最长长度。

用kmp的next数组枚举,用kmp判断当前长度的E串是否存在,不存在则往前跳

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<map>
#include<set>
#define lson i<<1
#define rson i<<1|1
using namespace std;
const int N=1e6+5;
char str[N];
int f[N];
void getnext(char *s)
{
    int n=strlen(s);
    f[0]=f[1]=0;
    for(int i=1;i<n;i++)
    {
        int j=f[i];
        while(j&&s[i]!=s[j])
            j=f[j];
        f[i+1]=(s[i]==s[j])?j+1:0;
    }
}
bool kmp(char *t,char *s,int n,int m)
{
    for(int i=0,j=0;i<n;i++)
    {
        while(j&&t[i]!=s[j])
            j=f[j];
        j+=(t[i]==s[j]);
        if (j==m) return true;
    }
    return false;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s",str);
        int len=strlen(str);
        getnext(str);
        int j=f[len];
        int ans=0;
        while(j)
        {
            if (len>=3*j&&kmp(str+j,str,len-2*j,j))
            {
                ans=j;
                break;
            }
            j=f[j];
        }
        printf("%d
",ans);
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/bk-201/p/7454979.html