Power Strings poj 2406(kmp&next找循环节)

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.

题意:给你一串字符串,问这串字符串最多是由几串相同的字符串组成。

思路:同样是next数组的运用,只需判断字符串的长度跟循环节是否是倍数关系。

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e6+10;
char a[N];
int net[N],len;
void getnext()
{
    net[0]=-1;
    int k=-1,j=0;
    while(j<len)
    {
        if(k==-1||a[j]==a[k])
            net[++j]=++k;
        else k=net[k];
    }
}
int main()
{
    int tmp;
    while(~scanf("%s",a)&&a[0]!='.')
    {
        len=strlen(a);
        getnext();
        tmp=len-net[len];
        if(len%tmp!=0) printf("1\n");
        else printf("%d\n",len/tmp);
    }
}

猜你喜欢

转载自blog.csdn.net/never__give__up/article/details/80402615