poj2406 Power Strings
地址:http://poj.org/problem?id=2406
题目:
Power Strings
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 47529 | Accepted: 19823 |
Description
Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).
Input
Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.
Output
For each s you should print the largest n such that s = a^n for some string a.
Sample Input
abcd
aaaa
ababab
.
Sample Output
1
4
3
Hint
This problem has huge input, use scanf instead of cin to avoid time limit exceed.
Source
思路:kmp+最小循环节
1 #include <cstdio>
2 #include <cstring>
3 #include <iostream>
4
5 using namespace std;
6
7 #define MP make_pair
8 #define PB push_back
9 typedef long long LL;
10 const double eps=1e-8;
11 const int K=1e6+7;
12 const int mod=1e9+7;
13
14 int nt[K];
15 char sa[K],sb[K];
16 void kmp_next(char *T,int *next)
17 {
18 next[0]=0;
19 for(int i=1,j=0,len=strlen(T);i<len;i++)
20 {
21 while(j&&T[i]!=T[j]) j=next[j-1];
22 if(T[i]==T[j]) j++;
23 next[i]=j;
24 }
25 }
26 int kmp(char *S,char *T,int *next)
27 {
28 int ans=0;
29 int ls=strlen(S),lt=strlen(T);
30 kmp_next(T,next);
31 for(int i=0,j=0;i<ls;i++)
32 {
33 while(j&&S[i]!=T[j]) j=next[j-1];
34 if(S[i]==T[j]) j++;
35 if(j==lt) ans++;
36 }
37 return ans;
38 }
39 int main(void)
40 {
41 while(1)
42 {
43 scanf("%s",sa);
44 if(sa[0]=='.')break;
45 kmp_next(sa,nt);
46 int len=strlen(sa);
47 int ans=len-nt[len-1];
48 printf("%d\n",len%ans?1:len/ans);
49 }
50 return 0;
51 }
作者:weeping
出处:www.cnblogs.com/weeping/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。