KMP算法

来源:互联网 发布:mac能打dota2吗 编辑:程序博客网 时间:2024/06/16 07:10

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

在杭电上看到了一道KMP算法的题目,于是捎带的学习了一下KMP算法,现贴上AC代码。

#include<iostream>using namespace std;long int a[1000001];long int b[10001];long int next[1000001];void nextfun(){    long int i=1;    long int j=0;    next[1]=0;    while(i < b[0])    {        if(0 == j || b[i] == b[j])        {            i++;            j++;            next[i] =j;        }        else            j = next[j];    }}int KMP(){    long int i=1,j=1;    while(i<=a[0] && j<=b[0])    {        if(a[i] == b[j] || 0 == j)        {            i++;            j++;        }        else            j = next[j];    }    if(j > b[0])        return (i - b[0]);    else        return -1;}int main(){    int t;    cin >> t;    while(t --)    {        cin >> a[0] >> b[0];        long int i;        for(i=1;i<=a[0];i++)        {            cin >> a[i];        }        for(i=1;i<=b[0];i++)            cin >> b[i];        nextfun();        cout<<KMP()<<endl;    }    return 0;}



原创粉丝点击