POJ 2406 Power Strings

本文针对PowerStrings问题,提出了一种基于失配数组的算法来确定输入字符串中最短循环节的出现次数。通过计算字符串的失配值,可以高效地找出循环节的长度及重复次数。

Power Strings
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 50920 Accepted: 21254

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

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

题意:输入字符串,问其中最短循环出现的次数。

解题思路:最短循环节的长度cir其实就是字符串的长度len减去最后一个字符的next值,也就是cir=len-next[len]。如果cir能够被len整除,那么循环节出现的次数就是len/cir。如果不能整除那么说明该循环节是第一次出现。

AC代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN = 1e6 + 10; //最大的字符串长度 
char str[MAXN];
int fail[MAXN];
void get_fail(int n) //失配数组 
{
	memset(fail,0,sizeof(fail));
	fail[0]=0; 
	fail[1]=0; 
	for(int i=1;i<n;i++)
	{
		int j=fail[i];
		while(j && str[i]!=str[j]) j=fail[j];
		fail[i+1]=str[i]==str[j]?j+1:0;
	}
}
void solve()
{
	int len=strlen(str); //字符串的长度 
	get_fail(len); //得到失陪数组 
	int cir=len-fail[len]; //最短的循环节长度 
	if(len%cir!=0) printf("1\n"); //第一次出现 
	else printf("%d\n",len/cir); //出现次数 
}
int main(void)
{
	while(gets(str)) //输入字符串 
	{
		if(str[0]=='.') break; //不满足要求,退出循环 
		solve(); //处理函数 
	}
	return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值