p.s. KMP.next数组循环节应用
Power Strings
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem 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
题目链接:
http://acm.sdut.edu.cn/onlinejudge2/index.php/Home/Contest/contestproblem/cid/2710/pid/2475
#include <bits/stdc++.h>
using namespace std;
int nextnum[1000010];
char s[1000010];
void get_next(char s[]){
int i=0,j=-1,len=strlen(s);
nextnum[0]=-1;
while(i<len)
{
if(j==-1||s[i]==s[j])
{
i++;
j++;
nextnum[i]=j;
}
else
j=nextnum[j];
}
}
int main()
{
while(cin >> s&&s[0]!='.')
{
int len=strlen(s);
get_next(s);
if(len%(len-nextnum[len])==0)
cout << len/(len-nextnum[len]) << endl;
else
cout << 1 << endl;
}
return 0;
}