UVA1328 Period
题目传送门
解题思路:
这道题其实就是求一个字符串的所有前缀及其本身的循环节(如果有),思路同另一道题.
AC代码:
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 5 using namespace std; 6 7 int n,tot,_next[1000001],j; 8 string l,p; 9 10 int main() { 11 while(true) { 12 tot++; 13 scanf("%d",&n); 14 if(n == 0) return 0; 15 cin >> p; 16 l = " " + p; 17 j = 0; 18 memset(_next,0,sizeof(_next)); 19 _next[1] = 0; 20 for(int i = 2;i <= n; i++) { 21 while(j != 0 && l[i] != l[j+1]) j = _next[j]; 22 if(l[i] == l[j+1]) j++; 23 _next[i] = j; 24 } 25 printf("Test case #%d\n",tot); 26 for(int i = 2;i <= n; i++) { 27 int u = i - _next[i]; 28 if(i % u == 0 && i != u) 29 printf("%d %d\n",i,i / u); 30 } 31 printf("\n"); 32 } 33 return 0; 34 }