poj 2406 Power Strings KMP

Power Strings

Time Limit: 20 Sec  Memory Limit: 256 MB

题目连接

http://poj.org/problem?id=2406

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

 

题意

找最小循环节的循环次数

题解:

KMP搞一搞就好了

代码:

 

//qscqesze
#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <typeinfo>
#include <fstream>
#include <map>
#include <stack>
typedef long long ll;
using namespace std;
//freopen("D.in","r",stdin);
//freopen("D.out","w",stdout);
#define sspeed ios_base::sync_with_stdio(0);cin.tie(0)
#define maxn 4000001
#define mod 10007
#define eps 1e-9
int Num;
char CH[20];
//const int inf=0x7fffffff;   //нчоч╢С
const int inf=0x3f3f3f3f;
/*

inline void P(int x)
{
    Num=0;if(!x){putchar('0');puts("");return;}
    while(x>0)CH[++Num]=x%10,x/=10;
    while(Num)putchar(CH[Num--]+48);
    puts("");
}
*/
inline ll read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
inline void P(int x)
{
    Num=0;if(!x){putchar('0');puts("");return;}
    while(x>0)CH[++Num]=x%10,x/=10;
    while(Num)putchar(CH[Num--]+48);
    puts("");
}
//**************************************************************************************

char s[maxn];
int p[maxn];
int main()
{
    while(scanf("%s",s+1)!=EOF){
        if(s[1]=='.')
        break;
    int len=strlen(s+1);
    int j=0;
    for(int i=2;i<=len;i++)
    {
        while(j>0&&s[j+1]!=s[i])
            j=p[j];
        if(s[j+1]==s[i])
            j++;
        p[i]=j;
    }
    int tmp=0;
    int first=1;
    if(len%(len-p[len]))
        puts("1");
    else
        printf("%d\n",len/(len-p[len]));
    }
}

 

posted @ 2015-05-07 13:33  qscqesze  阅读(537)  评论(0编辑  收藏  举报