poj 2752 Seek the Name, Seek the Fame (kmp 理解nxt函数)

poj 2752题目链接

题意:求出所有的前缀和后缀相同的子串的长度。

思路:求出nxt函数,观察发现,从从len递归向前就是答案。

 1/* ***********************************************
 2Author :111qqz
 3Created Time :2016年08月10日 星期三 21时05分52秒
 4File Name :code/poj/2752.cpp
 5************************************************ */
 6
 7#include <cstdio>
 8#include <cstring>
 9#include <iostream>
10#include <algorithm>
11#include <vector>
12#include <queue>
13#include <stack>
14#include <set>
15#include <map>
16#include <string>
17#include <cmath>
18#include <cstdlib>
19#include <deque>
20#include <ctime>
21#define fst first
22#define sec second
23#define lson l,m,rt<<1
24#define rson m+1,r,rt<<1|1
25#define ms(a,x) memset(a,x,sizeof(a))
26typedef long long LL;
27#define pi pair < int ,int >
28#define MP make_pair
29
30using namespace std;
31const double eps = 1E-8;
32const int dx4[4]={1,0,0,-1};
33const int dy4[4]={0,-1,1,0};
34const int inf = 0x3f3f3f3f;
35const int N=4E6+7;
36int n;
37string a;
38int nxt[N];
39void getnxt( int n)
40{
41    int i = 0 ;
42    int j = -1 ;
43    nxt[0] = -1;
44    while (i<n)
45	if (j==-1||a[i]==a[j]) nxt[++i]=++j;
46	else j = nxt[j];
47}
48void print( int x)
49{
50    if (nxt[x]!=-1)
51    {
52	print(nxt[x]);
53	printf("%d ",x);
54    }
55}
56int main()
57{
58	#ifndef  ONLINE_JUDGE 
59	freopen("code/in.txt","r",stdin);
60  #endif
61//	ios::sync_with_stdio(false);
62	while (cin>>a)
63	{
64	    int len = a.length();
65	    getnxt(len);
66	  //  for ( int i = 0 ; i < len ; i++) cout<<i<<" nxt[i]:"<<nxt[i]<<endl;
67	    print(nxt[len]);
68	    printf("%d\n",len);
69
70	}
71
72  #ifndef ONLINE_JUDGE  
73  fclose(stdin);
74  #endif
75    return 0;
76}