Hdu 2594(KMP)

Hdu传送门
连接s1,s2, kmp求前缀和后缀(给了两个字符串,有时可以连接解题 )

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
51
52
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define ms(i,j) memset(i, j, sizeof i);
const int MAXN = 50000 + 5;
char s1[MAXN*3], s2[MAXN];
int n1, n2, n, f[MAXN*3];
void init()
{
n1 = strlen(s1), n2 = strlen(s2);
n = n1 + n2;
for (int i=n1;i<n;i++)
{
s1[i] = s2[i-n1];
}
}
void solve()
{
f[0] = f[1] = 0;
for (int i=1;i<n;i++)
{
int j = f[i];
while (j && s1[i]!=s1[j]) j = f[j];
f[i+1] = (s1[i]==s1[j]) ? (j+1) : (0);
}
int i = n;
while (f[i])
{
if (f[i]<=min(n1,n2))
{
for (int j=0;j<f[i];j++) putchar(s1[j]);
printf(" %d\n", f[i]);
return ;
}
i = f[i];
}
printf("%d\n", 0);
}
int main()
{
while (scanf("%s%s", s1, s2)==2)
{
init();
solve();
}
return 0;
}

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