[LA3026]Period
生活随笔
收集整理的這篇文章主要介紹了
[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 3Test 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; }?
轉載于:https://www.cnblogs.com/xiao-ju-ruo-xjr/p/5753884.html
總結
以上是生活随笔為你收集整理的[LA3026]Period的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 博客园博客开通
- 下一篇: hdu 2191 多重背包