hdu_1358_kmp_next_数组简单应用

来源:互联网 发布:mindmap mac 破解版 编辑:程序博客网 时间:2024/06/05 09:23

题意:
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

告诉你字符串的长度,给你字符串s
让你求字符串1-i中可以存在k个子串构成i-i这个串;
输出当前i 和k;

解;
直接想到nxt数组求循环节,但是要考虑循环节根本不存在的情况,就是nxt[i]=0的情况;

#include<bits/stdc++.h>using namespace std;const int N=(int) 1e6+10;int m,nxt[N];void getnext(char *s){    int i=0,j=-1;    nxt[0]=-1;    while(i<m)    {        if(j==-1||s[i]==s[j])            nxt[++i]=++j;        else j=nxt[j];    }}int main(){    char s[N];    int t,i,j;    int k=0;    while(cin>>t&&t)    {        scanf("%s",s);        m=strlen(s);        getnext(s);        for(i=1;i<=m;i++)            cout<<i<<" "<<nxt[i]<<endl;        printf("Test case #%d\n",++k);        for(i=2; i<=t; i++)        {            int len=i-nxt[i];            if(i%len==0&&len!=i)            {                printf("%d %d\n",i,i/len);            }        }        puts("");    }    return 0;}
原创粉丝点击