POJ 1961

使用MP算法(而非KMP),以及字符串关于边界问题中出现的周期问题,详见本博客的文章字符串匹配章节

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

const int maxn= 1e6+5;

char ar[maxn];
int nxt[maxn];

void Kmp(int m)
{
	int i= 0, j;
	j= nxt[0]= -1;

	while (i< m){
		while (j> -1 && ar[i]!= ar[j]){
			j= nxt[j];
		}
		nxt[++i]= ++j;
	}
}
int main()
{
	int kase=1, n, pd;

	while (EOF!= scanf("%d", &n) && n){
		printf("Test case #%d\n", kase++);
		scanf(" %s", ar);

		Kmp(n);

		for (int i= 2; i<= n; ++i){
			if (0== (i%(i-nxt[i]))){
				pd= i/(i-nxt[i]);
				if (1!= pd){
					printf("%d %d\n", i, pd);
				}
			}
		}
		putchar('\n');
	}

	return 0;
}
posted @ 2020-03-18 22:48  IdiotNe  阅读(115)  评论(0编辑  收藏  举报