【POJ 2406】 Power Strings(KMP求循环节)

本文详细解析了POJ2406 PowerStrings问题的解决方法,利用KMP算法寻找字符串的循环节,介绍了Next数组的含义及其在解决此问题中的应用,并提供了完整的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【POJ 2406】 Power Strings(KMP求循环节)

Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 40536 Accepted: 16862

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.

Source


之前只在比赛中接触到过循环节,还蛮频繁的。当时直接夹杂出来个最小表示。。当时挺懵的。专题做到KMP这里,惊喜的发现是个循环节(虽然起初不是按循环节写的。。。

对KMP理解突然加深了一大截,不过起初用了种类似dp的方法,借用了之前的状态(由于先写的1961 直接抓来同样的代码改改交了 发现时间好久 然后才明白了……


首先对于Next数组,Next[i]其实实在i-1上建立的,也就是i-1与其应匹配的位置上的字符匹配,如果不同就往前找,直到找到第一个匹配的字符str[j],或者找到串首,然后给Next[i]赋值j+1 表示i失配后应和str[j+1]比较

这样来看,如果通过Next来找第i个字符往前的最早匹配,其实应该观察Next[i+1] 这样其实从Next[i+1]-1到i间就是前缀串i的重复子串 也就是长为i的前缀的模式串

那么题中所求的就是长为len的前缀的模式串 也就是len/Next[len](Next数组下标从0开始


代码如下:

#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <list>
#include <algorithm>
#include <map>
#include <set>
#define LL long long
#define Pr pair<int,int>
#define fread() freopen("in.in","r",stdin)
#define fwrite() freopen("out.out","w",stdout)

using namespace std;
const int INF = 0x3f3f3f3f;
const int msz = 10000;
const int mod = 1e9+7;
const double eps = 1e-8;

char str[2333333];
int Next[2333333];
int n;

void GetNext()
{
	int j,i = 0;
	j = Next[0] = -1;

	while(i < n)
	{
		while(j != -1 && str[i] != str[j]) j = Next[j];
		++i,++j;
		Next[i] = j;
	}
}

int main()
{
	//fread();
	//fwrite();

	while(~scanf("%s",str) && str[0] != '.')
	{
		n = strlen(str);
		GetNext();

		printf("%d\n",(n%(n-Next[n]) == 0)? n/(n-Next[n]): 1);
	}

	return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值