G - Power Strings

时间:2019-01-18
本文章向大家介绍G - Power Strings,主要包括G - Power Strings使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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: a0 = “” (the empty string) and a(n+1) = a*(an).

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.

思路:
由定理:假设S的长度为len,则S存在循环子串,当且仅当,len可以被len - F[len]整除,最短循环子串为S[len - F[len]]可推出

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <algorithm>
using namespace std;
const int N=1000005;
int F[N];
char a[N],b[N];
void getF (char *P, int m)
{
    F[1]=0;
    for(int i=2;i<=m;i++)
    {
        int k=F[i-1];
        while(k&&P[k+1]!=P[i]) k=F[k];
        if(P[k+1]==P[i]) k++;
        F[i]=k;
    }
}
int main()
{
    while(scanf("%s",a+1),strcmp(a+1,"."))
    {
        int al=strlen(a+1);
        getF(a,al);
        if(al%(al-F[al])==0) printf("%d\n",al/(al-F[al]));
        else printf("1\n");
    }
    return 0;
}