码迷,mamicode.com
首页 > 编程语言 > 详细

hdu1358 kmp的next数组

时间:2017-05-04 22:03:58      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:题意   incr   nat   asc   tween   open   file   display   cout   

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 A K , that is A concatenated K times, for some string A. Of course, we also want to know the period K. 

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;
}
View Code

 

hdu1358 kmp的next数组

标签:题意   incr   nat   asc   tween   open   file   display   cout   

原文地址:http://www.cnblogs.com/acjiumeng/p/6809385.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!