codeforces 93 div2 D题 - kmp- 3

http://codeforces.com/contest/127/problem/D
password
题意:输入一个字符串,求一个最长的子串,使得其既是原串的前缀,也是后缀,也是一个非前后缀的子串

分析:要求一个串既是前缀,也是后缀,则用kmp可以很容易解决,这个前缀一定是其后缀所能匹配的所有前缀中的一个,找到其中一个最长的、而且也可以被后面另一个位置的匹配的前缀即可

对kmp至今没理解清楚啊。。


代码:

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

const int N=1000010;
int n, next[N], c[N];
char s[N];

void getnext(char *s, int n)
{
    int i, k;
    k = -1;
    i = 0;
    next[i] = -1;
    while(i<n)
    {
        if(k==-1 || s[i]==s[k])
        {
            next[++i] = ++k;
        }
        else
            k = next[k];
    }
}

int main()
{
    int i, j, k, ans;
    while(scanf("%s", s)!=EOF)
    {
        n = strlen(s);
        getnext(s, n);

        for(i=1; i<=n; i++)
            c[i] = 0;
        for(i=n-1; i>=1; i--)
        {
            c[next[i]] += c[i]+1;
        }

        j = next[n];
        while(j!=0)
        {
            if(c[j]>=1)
                break;
            j = next[j];
        }
        if(j==0)
            printf("Just a legend\n");
        else
        {
            s[j] = 0;
            printf("%s\n", s);
        }
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/ggggiqnypgjg/article/details/6966269