hdu1358 kmp的next数组
Posted walfy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu1358 kmp的next数组相关的知识,希望对你有一定的参考价值。
InputThe input file consists of several test cases. Each test case consists of two lines. The first one contains N (2 <= N <= 1 000 000) ?C 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.
OutputFor 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
题意:给一个字符串你,前i个中找有循环的位置和循环次数,具体看样例
题解:用Next数组求i位置的环,用i-Next【i】求,遍历数组就好了
#include<map> #include<set> #include<cmath> #include<queue> #include<stack> #include<vector> #include<cstdio> #include<iomanip> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> #define pi acos(-1) #define ll long long #define mod 1000000007 #define ls l,m,rt<<1 #define rs m+1,r,rt<<1|1 using namespace std; const double g=10.0,eps=1e-9; const int N=1000000+5,maxn=1000000+5,inf=0x3f3f3f3f; int Next[N],n; string str; void getnext() { int k=-1; Next[0]=-1; for(int i=1;i<n;i++) { while(k>-1&&str[k+1]!=str[i])k=Next[k]; if(str[k+1]==str[i])k++; Next[i]=k; } } int main() { ios::sync_with_stdio(false); cin.tie(0); // cout<<setiosflags(ios::fixed)<<setprecision(2); int cnt=0; while(cin>>n,n){ cin>>str; getnext(); /* for(int i=0;i<n;i++) cout<<Next[i]<<" "; cout<<endl;*/ cout<<"Test case #"<<++cnt<<endl; for(int i=1;i<n;i++) { if(Next[i]!=-1) { int loop=i-Next[i]; // cout<<loop<<endl; if((i+1)%loop==0)cout<<i+1<<" "<<(i+1)/loop<<endl; } } cout<<endl; } return 0; }
以上是关于hdu1358 kmp的next数组的主要内容,如果未能解决你的问题,请参考以下文章
Period HDU 1358 KMP next数组性质的应用