[LA3026]Period

[LA3026]Period

试题描述

For each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, inclusive), we want to know whether the prefix is a periodic string. That is, for each i (2 ≤ i ≤ N) we want to know the largest K > 1 (if there is one) such that the prefix of S with length i can be written as AK, that is A concatenated K times, for some string A. Of course, we also want to know the period K.

输入

The input file consists of several test cases. Each test case consists of two lines. The first one contains N (2 ≤ N ≤ 1000000) the size of the string S. The second line contains the string S. The input file ends with a line, having the number zero on it.

输出

For each test case, output ‘Test case #’ and the consecutive test case number on a single line; then, for each prefix with length i that has a period K > 1, output the prefix size i and the period K separated by a single space; the prefix sizes must be in increasing order. Print a blank line after each test case.

输入示例

3
aaa
12
aabaabaabaab
0

输出示例

Test case #1
2 2
3 3

Test case #2
2 2
6 2
9 3
12 4

数据规模及约定

见“输入

题解

KMP 裸题,对于位置 i,它指向的失配的位置为 f[i+1],那么当 f[i+1] > 1 且 (i - f[i+1] + 1) | i 时答案为 i / (i - f[i+1] + 1). 我 KMP 从 1 开始做的所以前面的式子可能会奇怪一些。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <cstring>
#include <string>
#include <map>
#include <set>
using namespace std;

int read() {
    int x = 0, f = 1; char c = getchar();
    while(!isdigit(c)){ if(c == '-') f = -1; c = getchar(); }
    while(isdigit(c)){ x = x * 10 + c - '0'; c = getchar(); }
    return x * f;
}

#define maxn 1000010
int n, f[maxn];
char S[maxn];

int main() {
	n = read();
	int kase = 0; // bool fl = 1;
	while(n) {
		scanf("%s", S + 1);
//		if(!fl) putchar('\n'); fl = 0;
		printf("Test case #%d\n", ++kase);
		f[1] = f[2] = 1;
		for(int i = 2; i <= n; i++) {
			int u = f[i];
			while(u > 1 && S[u] != S[i]) u = f[u];
			f[i+1] = S[u] == S[i] ? u + 1 : u;
			if(f[i+1] > 1 && i % (i + 1 - f[i+1]) == 0) printf("%d %d\n", i, i / (i + 1 - f[i+1]));
		}
		putchar('\n');
		n = read();
	}
	
	return 0;
}

 

posted @ 2016-08-09 16:57  xjr01  阅读(187)  评论(0编辑  收藏  举报