CDOJ 1065 全都是秋实大哥 KMP

给你一个字符串,求它各个前缀的最小循环节长度,和输出它本身的最小循环节

用KMP算法的next数组,,,现在也不是很理解,,先贴代码。。。


代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
using namespace std;
#define maxn 3000003
char str[maxn];
int n, then[maxn];
void get_then()
{
	int i = 0, j = -1;
	then[0] = -1;
	while (i < n)
	{
		if (j == -1 || str[i] == str[j])
		{
			++i;
			++j;
			then[i] = j;
		}
		else
			j = then[j];
	}
}
int main()
{
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	scanf("%s", str);
	n = strlen(str);
	get_then();
	for (int i = 1; i < n; ++i)
	{
		if (i % (i - then[i]) == 0)
			printf("%d ", i - then[i]);
		else
			printf("%d ", i);
	}
	int len = 0;
	if (n % (n - then[n]) == 0)
	{
		len = n - then[n];
		printf("%d\n", len);
	}
	else
	{
		len = n;
		printf("%d\n", len);
	}
	for (int i = 0; i < len; ++i)
		putchar(str[i]);
	//while (1);
	return 0;
}

你可能感兴趣的:(CDOJ 1065 全都是秋实大哥 KMP)