码迷,mamicode.com
首页 > 其他好文 > 详细

POJ2406 Power Strings(循环节)

时间:2021-01-26 11:47:12      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:amp   not   should   test   print   one   rip   元素   main   

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.

假设一个字符串是由K个子串组成的,
则字符串最后一个字符的NEXT数值一定是K-1个子串的长度,
(next数组是"前缀"和"后缀"的最长的共有元素的长度,
那最后一个字符的next数值就是整个字符串中前缀和后缀最长共有元素的值)
所以只需求出NEXT[N]后N-NEXT[N]就是可能的最小循环节,
但是如果N-NEXT[N]不能整除N,则一定原字符串无循环.
定理:
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]。

#include <string.h>
#include <stdio.h>
#include <math.h>
#include <algorithm>
using namespace std;
const int maxn=1e6;
int nxt[maxn],l;
char s[maxn];
void getnext()
{
	int i=0,j=-1;
	nxt[0]=-1;
	while(i<l)
	{
		if (j==-1||s[i]==s[j])
		{
			i++;
			j++;
			nxt[i]=j;
		}
		else
		j=nxt[j];
	}
}
int main()
{
	int i,j,n;
	while(~scanf("%s",s)&&s[0]!=‘.‘)
	{
		l=strlen(s);
		getnext();
		int len=l-nxt[l]; 
		if (l%len==0)
		printf("%d\n",l/len);
		else
		printf("1\n"); 	
	}

	return 0;
}

POJ2406 Power Strings(循环节)

标签:amp   not   should   test   print   one   rip   元素   main   

原文地址:https://www.cnblogs.com/shidianshixuan/p/14319327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!