HDU 1171 Number Sequence(KMP)

Number Sequence

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1711

解题思路:

不想说我对kmp算法懂了多少,但至少理解了。能敲出代码。给你几个大牛的博客,看看他们对kmp的理解:

http://kb.cnblogs.com/page/176818/

http://www.cnblogs.com/dolphin0520/archive/2011/08/24/2151846.html

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int n,m;
int a[1000005],b[10005];

void getnext(int *p,int *next){
    int j = 0,k = -1;
    next[0] = -1;
    while(j < m-1){
        if(k == -1 || p[j] == p[k]){
            j++;k++;
            next[j] = k;
        }
        else{
            k = next[k];
        }
    }
}

void kmp(int *s,int *p){
    int i = 0,j = 0;
    int next[10005];
    getnext(p,next);
    while(i < n){
        if(j == -1 || s[i] == p[j]){
            i++;
            j++;
        }
        else{
            j = next[j];
        }
        if(j == m){
            printf("%d\n",i-m+1);
            return ;
        }
    }
    printf("-1\n");
}

int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&n,&m);
        for(int i = 0; i < n; i++)
            scanf("%d",&a[i]);
        for(int i = 0; i < m; i++)
            scanf("%d",&b[i]);
        kmp(a,b);
    }
    return 0;
}


你可能感兴趣的:(KMP)