Cyclic Nacklace

题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=3746

解题思路: 如果一个串是符合条件的,那么在两端的哪一端加入字符结果都是一样的。例如,"abcabcab"。所以,我们只需要找到字符串的循环节,然后补齐剩下的部分即可。这正是next数组可以做的。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int imax_n = 1000005;
 5 
 6 int next_[imax_n];
 7 char s[imax_n];
 8 int n;
 9 
10 void get_next(char *s)
11 {
12     int i = 0, j = -1;
13     next_[i] = j;
14     while (i < n)
15     {
16         while (-1 != j && s[i] != s[j]) j = next_[j];
17         next_[++i] = ++j;
18     }
19 }
20 
21 int main()
22 {
23     int Case;
24     scanf("%d", &Case);
25     while (Case--)
26     {
27         scanf("%s", s);
28         n = strlen(s);
29         get_next(s);
30         int d = n - next_[n];
31         if (d != n && n % d == 0)
32         {
33             printf("0
");
34         }
35         else
36         {
37             printf("%d
", d - (n - n / d * d));
38         }
39     }
40     return 0;
41 }
原文地址:https://www.cnblogs.com/djingjing/p/8672684.html