hdu 1358 Period(kmp)
Posted wmj6
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu 1358 Period(kmp)相关的知识,希望对你有一定的参考价值。
Problem Description
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.
Input
The input file consists of several test cases. Each test case consists of two lines. The first one contains N (2 <= N <= 1 000 000) – 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.
Output
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.
Sample Input
3
aaa
12
aabaabaabaab
0
Sample Output
Test case #1
2 2 3 3
Test case #2
2 2 6 2 9 3 12 4
题意:找每个前缀的最小循环节,如果有就输出位置和循环次数
思路:kmp
#include <cstdio> #include <map> #include <iostream> #include<cstring> #include<bits/stdc++.h> #define ll long long int #define M 6 using namespace std; inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;} inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;} int moth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; int dir[4][2]={1,0 ,0,1 ,-1,0 ,0,-1}; int dirs[8][2]={1,0 ,0,1 ,-1,0 ,0,-1, -1,-1 ,-1,1 ,1,-1 ,1,1}; const int inf=0x3f3f3f3f; const ll mod=1e9+7; int nextt[1000007]; void getnext(string s){ nextt[1]=0; int len=s.length(); for(int i=2,j=0;i<=len;i++){ while(j>0&&s[i-1]!=s[j]) j=nextt[j]; if(s[i-1]==s[j]) j++; nextt[i]=j; } } int main(){ ios::sync_with_stdio(false); int n; int cnt=0; while(cin>>n&&n){ string s; cin>>s; getnext(s); int len=s.length(); cout<<"Test case #"<<++cnt<<endl; for(int i=2;i<=len;i++){ if(nextt[i]==0) continue; int t=i-nextt[i]; if(i%t==0){ cout<<i<<" "<<i/t<<endl; } } cout<<endl; } return 0; }
以上是关于hdu 1358 Period(kmp)的主要内容,如果未能解决你的问题,请参考以下文章
HDU-1358 Period 字符串问题 KMP算法 求最小循环节