POJ 2406 KMP (循环节

版权声明:欢迎加好友讨论~ QQ1336347798 https://blog.csdn.net/henu_xujiu/article/details/81780552

题目链接

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.

与上一篇博客讲的一样只需要稍微改动即可

上一篇

ac代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
int next[1100000] ;
char str[1100000] ;
void getnext(int l)//next
{
    int j = 0 , k = -1 ;
    next[0] = -1 ;
    while(j < l)
    {
        if( k == -1 || str[j] == str[k] )
        {
            j++ ;
            k++ ;
            next[j] = k ;
        }
        else
            k = next[k] ;
    }
}
int main()
{

    while(cin>>str)
    {
        if( str[0] == '.' ) break;
        int len = strlen(str);
        getnext(len) ;
      //  for(int i=0;i<len;i++)
        //	cout<<next[i]<<" ";
        if( len % (len-next[len]) == 0 )
            cout<<len/(len-next[len])<<endl;//循环节有几位 
        else
        	cout<<1<<endl;
        memset(str,0,sizeof(str));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/henu_xujiu/article/details/81780552