码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 4763 Theme Section(KMP)

时间:2015-02-03 17:13:18      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:acm   kmp   

解题思路:

只需要判断中间是否存在和前缀后缀相等的字符串即可。

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <set>
using namespace std;
const int maxn = 1000000 + 10;
char s[maxn];
int next[maxn];
void get_next()
{
    int m = strlen(s);
    next[0] = 0; next[1] = 0;
    for(int i=1;i<m;i++)
    {
        int j = next[i];
        while(j && s[i] != s[j]) j = next[j];
        next[i+1] = (s[i] == s[j]) ? j + 1 : 0;
    }
}
bool KMP(char *p, char *t, int n, int m)
{
    int i , j;
    for(i=0,j=0;i<n;i++)
    {
        while(j && t[j] != p[i]) j = next[j];
        if(t[j] == p[i]) j++;
        if(j == m) return 1;
    }
    return 0;
}
int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%s", s);
        get_next();
        int n = strlen(s);
        int j = next[n];
        int ans = 0;
        while(j)
        {
            if(n >= 3 * j && KMP(s+j,s,n-2*j,j))
            {
                ans = j;
                break;
            }
            j = next[j];
        }
        printf("%d\n", ans);
    }
    return 0;
}

HDU 4763 Theme Section(KMP)

标签:acm   kmp   

原文地址:http://blog.csdn.net/moguxiaozhe/article/details/43451705

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!