POJ 2406 Power Strings(kmp)
预处理改一下,就OK了。。。我竟然敲错模版了。。。3Y。一种是暴力,一种更巧妙。
直接取余判断
1 #include <stdio.h> 2 #include <string.h> 3 #define N 1000001 4 char str[N]; 5 int next[N]; 6 int main() 7 { 8 int i,j,len,d; 9 while(scanf("%s",str)!=EOF) 10 { 11 if(str[0] == '.')break; 12 len = strlen(str); 13 next[0] = -1; 14 j = -1; 15 for(i = 1;i <= len-1;i ++) 16 { 17 while(j >= 0&&str[j+1] != str[i]) 18 j = next[j]; 19 if(str[j+1] == str[i]) j++; 20 next[i] = j; 21 } 22 d = len-1-next[len-1]; 23 if(len % d == 0)//开始的时候没加,WA了,用暴力水过了 24 printf("%d\n",len/d); 25 else 26 printf("1\n"); 27 } 28 return 0; 29 }
暴力
1 #include <stdio.h> 2 #include <string.h> 3 #define N 1000001 4 char str[N]; 5 int next[N]; 6 int main() 7 { 8 int i,j,len,num,d,z; 9 while(gets(str)!=0) 10 { 11 memset(next,0,sizeof(next)); 12 if(str[0] == '.')break; 13 len = strlen(str); 14 next[0] = -1; 15 j = -1; 16 num = 1; 17 for(i = 1;i <= len-1;i ++) 18 { 19 while(j >= 0&&str[j+1] != str[i]) 20 j = next[j]; 21 if(str[j+1] == str[i]) j++; 22 next[i] = j; 23 } 24 d = len-1-next[len-1]; 25 if(d != len) 26 num ++; 27 z = 1; 28 for(i = next[len-1];;i -= d) 29 { 30 if(d == i-next[i]&&next[i] != -1) 31 { 32 num ++; 33 } 34 else if(d == i+1&&next[i] == -1) 35 { 36 break; 37 } 38 else 39 { 40 z = 0; 41 break; 42 } 43 } 44 if(z) 45 printf("%d\n",num); 46 else 47 printf("%d\n",1); 48 } 49 return 0; 50 }