poj 2752(KMP)

poj 2752
1、注意f数组的意思就是前缀和后缀最长公共部分长度,灵话运用解题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define ms(i,j) memset(i, j, sizeof i);
const int MAXN = 400000 + 5;
char s[MAXN];
int f[MAXN], n, ans[MAXN], tot;
void init()
{
n = strlen(s);
}
void solve()
{
f[0] = f[1] = 0;
for (int i=1;i<n;i++)
{
int j = f[i];
while (j && s[i]!=s[j]) j = f[j];
f[i+1] = (s[i]==s[j]) ? (j+1) : (0);
}
int i = n; tot = 0;
while (i)
{
int xh = i - f[i];
ans[++tot] = i;
i = f[i];
}
bool flag = false;
for (int i=tot;i>0;i--)
{
if (flag) printf(" ");
printf("%d", ans[i]);
flag = true;
}
printf("\n");
}
int main()
{
while (scanf("%s", s)==1)
{
init();
solve();
}
return 0;
}

------ 本文结束 ------