Hdu 3746(KMP)

Hdu 3746
注意一下分类讨论

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
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
#define ms(i,j) memset(i, j, sizeof i);
const int MAXN = 100000 + 5;
int n, f[MAXN];
char s[MAXN];
void init()
{
scanf("%s", s);
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 xh = n - f[n];
if (xh==n) printf("%d\n", n);
else if (n%xh==0) printf("%d\n", 0);
else printf("%d\n", xh*(n/xh+1)-n);
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
init();
solve();
}
return 0;
}

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