您的位置:首页 > 其它

poj2406 power strings

2017-05-29 12:29 274 查看
Power Strings

Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 48385 Accepted: 20137
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.

要找字符串的循环接 

利用next数组  里面存的是这一位之前的最大前后缀长度 。如果这个长度乘二等于字符串长度 那么正好两个。

如果大于 则说明有交叉的部分 此时 len-next[len]就是这个循环节的长度

#include <iostream>

#include<cstdio>

#include<cstring>

using namespace std;

char a[1000005];

int n[1000005];

void kmp(int len)

{

    n[0]=-1;

    int k=-1;

    int j=0;

    while(j<=len)

    {

        if(k==-1||a[j]==a[k])

        {

            k++;

            j++;

            n[j]=k;

        }

        else k=n[k];

    }

}

int main()

{

    while(~scanf("%s",a))

    {

        if(a[0]=='.')break;

        int len=strlen(a);

        //memset(n,0,sizeof(n));

        kmp(len);

        if(len%(len-n[len])==0)

        cout<<len/(len-n[len])<<endl;

        else cout<<"1"<<endl;

    }

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: