标签:
参考:http://www.cnblogs.com/jackge/archive/2013/01/05/2846006.html
总结一下,如果对于next数组中的 i, 符合 i % ( i - next[i] ) == 0 && next[i] != 0 , 则说明字符串循环,而且
循环节长度为: i - next[i]
循环次数为: i / ( i - next[i] )
1 #include <iostream> 2 #include <cstdio> 3 #include <cmath> 4 #include <vector> 5 #include <cstring> 6 #include <string> 7 #include <algorithm> 8 #include <string> 9 #include <set> 10 #include <functional> 11 #include <numeric> 12 #include <sstream> 13 #include <stack> 14 #include <map> 15 #include <queue> 16 #pragma comment(linker, "/STACK:102400000,102400000") 17 #define CL(arr, val) memset(arr, val, sizeof(arr)) 18 19 #define ll long long 20 #define inf 0x7f7f7f7f 21 #define lc l,m,rt<<1 22 #define rc m + 1,r,rt<<1|1 23 #define pi acos(-1.0) 24 25 #define L(x) (x) << 1 26 #define R(x) (x) << 1 | 1 27 #define MID(l, r) (l + r) >> 1 28 #define Min(x, y) (x) < (y) ? (x) : (y) 29 #define Max(x, y) (x) < (y) ? (y) : (x) 30 #define E(x) (1 << (x)) 31 #define iabs(x) (x) < 0 ? -(x) : (x) 32 #define OUT(x) printf("%I64d\n", x) 33 #define lowbit(x) (x)&(-x) 34 #define Read() freopen("a.txt", "r", stdin) 35 #define Write() freopen("b.txt", "w", stdout); 36 #define maxn 1000000000 37 #define N 2510 38 #define mod 1000000000 39 using namespace std; 40 41 char a[1000010]; 42 int p[1000010]; 43 void next(int l) 44 { 45 int j=0; 46 p[1]=0; 47 for(int i=2;i<=l;i++) 48 { 49 while(j>0&&(a[j+1]!=a[i])) j=p[j]; 50 if(a[j+1]==a[i]) j+=1; 51 p[i]=j; 52 } 53 } 54 int main() 55 { 56 //freopen("a.txt","r",stdin); 57 int n,j=1; 58 while(~scanf("%d",&n)) 59 { 60 if(n==0) break; 61 printf("Test case #%d\n",j++); 62 scanf("%s",a+1); 63 int l=strlen(a+1); 64 next(l); 65 for(int i=1;i<=l;i++) 66 { 67 if(i%(i-p[i])==0&&p[i]!=0) 68 { 69 printf("%d %d\n",i,i/(i-p[i])); 70 } 71 } 72 printf("\n"); 73 } 74 return 0; 75 }
Uvalive - 3026 Period (kmp求字符串的最小循环节+最大重复次数)
标签:
原文地址:http://www.cnblogs.com/nowandforever/p/4601459.html