fzu 1901 Period II

next数组的应用,假设字符串长度为len,则next[len]的值为整个字符串的最长前后缀的长度。

len - next[len]即为题目所求p

#include<stdio.h>
#include<string.h>
const int maxn = 1e6+10;
char s[maxn];
int len,next[maxn];
int ans[maxn];

void getNext()
{
	next[0] = -1;
	int i = 0,j = -1;
	while(i < len)
	{
		if(j == -1 || s[i] == s[j])
			next[++i] = ++j;
		else j = next[j];
	}
}

int main()
{
	int T,cas = 0;
	scanf("%d",&T);
	while(T--)
	{
		int as = 0;
		scanf("%s",s);
		len = strlen(s);
		getNext();
		int tmp = next[len];
		int i = 0;
		while(tmp > 0)
		{
			ans[i++] = len - tmp;
			tmp = next[tmp];
			as++;
		}
		printf("Case #%d: %d\n",++cas,++as);
		for(int j = 0;j < i;j++)
			printf("%d ",ans[j]);
		printf("%d\n",len);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/feynmanz/article/details/80445646