poj 2752 Seek the Name, Seek the Fame (kmp 理解nxt函数)
题意:求出所有的前缀和后缀相同的子串的长度。
思路:求出nxt函数,观察发现,从从len递归向前就是答案。
/* ***********************************************
Author :111qqz
Created Time :2016年08月10日 星期三 21时05分52秒
File Name :code/poj/2752.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <stack>
8#include <set>
9#include <map>
10#include <string>
11#include <cmath>
12#include <cstdlib>
13#include <deque>
14#include <ctime>
15#define fst first
16#define sec second
17#define lson l,m,rt<<1
18#define rson m+1,r,rt<<1|1
19#define ms(a,x) memset(a,x,sizeof(a))
20typedef long long LL;
21#define pi pair < int ,int >
22#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=4E6+7;
7int n;
8string a;
9int nxt[N];
10void getnxt( int n)
11{
12 int i = 0 ;
13 int j = -1 ;
14 nxt[0] = -1;
15 while (i<n)
16 if (j==-1||a[i]==a[j]) nxt[++i]=++j;
17 else j = nxt[j];
18}
19void print( int x)
20{
21 if (nxt[x]!=-1)
22 {
23 print(nxt[x]);
24 printf("%d ",x);
25 }
26}
27int main()
28{
29 #ifndef ONLINE_JUDGE
30 freopen("code/in.txt","r",stdin);
31 #endif
32// ios::sync_with_stdio(false);
33 while (cin>>a)
34 {
35 int len = a.length();
36 getnxt(len);
37 // for ( int i = 0 ; i < len ; i++) cout<<i<<" nxt[i]:"<<nxt[i]<<endl;
38 print(nxt[len]);
39 printf("%d\n",len);
}
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}