Top

HDU-3746-Cyclic Nacklace (KMP求循环节)


博主链接

题目链接

Sample Input

1
2
3
4
5
>3
>aaa
>abca
>abcde
>

Sample Output

1
2
3
4
> 0
> 2
> 5
>

题意:

给你一些串,问如果想让这个串里面的循环节至少循环两次,需要添加几个字符(只能在最前面或者最后面添加)。比如ababc 需要添加5个就是添加ababc。

题解:

利用Next数组的性质:

符合 i % ( i - next[i] ) == 0 && next[i] != 0 , 则**说明字符串循环,而且**

循环节长度为: i - next[i]

循环次数为: i / ( i - next[i] )

代码:

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
#include <stdio.h>
#include <string.h>
const int N = 1e5+5;
int n, next[N];
char str[N];
void getNext () {
n = strlen (str+1);
int p = 0;
for (int i = 2; i <= n; i++) {
while (p > 0 && str[p+1] != str[i])
p = next[p];

if (str[p+1] == str[i])
p++;
next[i] = p;
}
}
int main () {
int cas;
scanf("%d", &cas);
while (cas--) {
scanf("%s", str+1);
getNext();
int n= strlen (str+1);
if (next[n] == 0) printf("%d\n", n);
else {
int k = n - next[n];
if (n%k == 0) printf("0\n");
else printf("%d\n", k - (n - (n/k) * k));
}
}
return 0;
}


未经允许不得转载: Anoyer's Blog » HDU-3746-Cyclic Nacklace (KMP求循环节)