您的位置:首页 > 其它

Power Strings(POJ-2406)(KMP简单循环节)

2017-08-23 08:55 369 查看
Power Strings

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

题目链接:http://poj.org/problem?id=2406

题目大意:给出一个字符串 问它最多由多少相同的字串组成 

4000

      如  abababab由4个ab组成

题目分析:要用到KMP中的next数组来计算最小循环节。

KMP最小循环节、循环周期:

定理:假设S的长度为len,则S存在最小循环节,循环节的长度L为len-next[len],子串为S[0…len-next[len]-1]。

(1)如果len可以被len - next[len]整除,则表明字符串S可以完全由循环节循环组成,循环周期T=len/L。

(2)如果不能,说明还需要再添加几个字母才能补全。需要补的个数是循环个数L-len%L=L-(len-L)%L=L-next[len]%L,L=len-next[len]。
讲解KMP循环节非常不错的博主  不懂得可以点进去。

代码:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <vector>
using namespace std;
typedef long long LL;
const int N=1000000+999;
char s2
;
int nex
;
void makeNext(int m)
{
int i,j;
nex[0] = 0;
for (i = 1,j = 0; i < m; i++)
{
while(j > 0 && s2[i] != s2[j])
j = nex[j-1];
if (s2[i] == s2[j])
j++;
nex[i] = j;
}
}
int main()
{
int n;
while(scanf(" %s",s2)!=EOF)
{
if(s2[0]=='.') break;
n=strlen(s2);
memset(nex,0,sizeof(nex));
makeNext(n);
int j=nex[n-1]; //1到n-1的最长前缀后缀相等长度
int ans=1;
if(n%(n-j)==0) //判断是否能由循环节组成
ans=n/(n-j); //由几个循环节构成
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: