您的位置:首页 > 其它

【POJ2406】 Power Strings (KMP)

2016-07-20 16:27 357 查看

Power Strings
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.



【题意】
  一个字符串的最大重复字串。
  即一个字符串是一个子串最多重复多少次得到的。

【分析】
  
  ① len==1||s[next[len-1]]!=s[len-1] ans=1;
  ② len%(len-next[len])==0 ans= len/(len-next[len]);

  原因如图:

  

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
#define Maxn 1000010

char s[Maxn];
int len,nt[Maxn];

void kmp()
{
nt[1]=0;
int p=0;
for(int i=2;i<=len;i++)
{
while(s[i]!=s[p+1]&&p) p=nt[p];
if(s[i]==s[p+1]) p++;
nt[i]=p;
}
}

int main()
{
int n,i;
while(1)
{
gets(s+1);
len=strlen(s+1);
if(len==1&&s[1]=='.') break;
kmp();
if(len%(len-nt[len])==0) printf("%d\n",len/(len-nt[len]));
else printf("1\n");
}
}


[POJ2406]

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