poj 2752_Seek the Name, Seek the Fame_KMP

来源:互联网 发布:网络推广微信营销方案 编辑:程序博客网 时间:2024/06/05 10:14

题目大意

找出一个字符串中既是前缀也是后缀的字串的长度


思路

利用KMP中next数组的种种玄学性质然后递归输出即可


#include <stdio.h>#include <string>#include <iostream>using namespace std;char a[500000];int p[500000];int print(int x){    if (p[x] > -1)    {        print(p[x]);        printf("%d ", p[x]+1);    }    return 0;}int main(){    while (gets(a) != NULL)    {        int n = strlen(a);        int j = -1;        p[0] = -1;        for (int i = 1; i < n; i++)        {            while (a[j + 1] != a[i] && j != -1) j = p[j];            if (a[j + 1] == a[i]) j++;            p[i] = j;        }        print(n - 1);        printf("%d ", n);    }    return 0;}
原创粉丝点击