当前位置: 代码迷 >> 综合 >> 求循环节Power Strings
  详细解决方案

求循环节Power Strings

热度:49   发布时间:2023-11-23 13:19:14.0

Power Strings

Description
Given two strings a and b we define ab to be their concatenation. For example, if a = “abc” and b = “def” then ab = “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
.
Output
1
4
3
Hint
This problem has huge input, use scanf instead of cin to avoid time limit exceed.
就是求最多循环节的问题,KMP算法以后就是比较简单,板子题

#include<bits/stdc++.h>
using namespace std;
string a;
int prefix[10000000];
void getprefix(int x)  //得到kmp的prefi数组,算法核心
{
    int now = -1;int i=0;prefix[i]=now;while(i<x){
    if(now==-1||a[i]==a[now])  //如果是一开始或者字符两者相等,进行后移操作,并得到数组prefix[++i]=(++now);else  //改变now的位置now=prefix[now];}/*cout<<i<<"**"<<endl;for(int j=0;j<=i;j++)cout<<prefix[j]<<endl;*/
}  
int main()
{
    while(cin>>a){
    if(a==".")break;int len=a.size();getprefix(len);// cout<<prefix[len]<<endl;if(len%(len-prefix[len])==0)  //len-prefix[len]就是循环节的大小cout<<len/(len-prefix[len])<<endl;elsecout<<1<<endl;}
}
  相关解决方案