[kmp] hdu1711 字符串匹配模板

Number Sequence

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 13568    Accepted Submission(s): 6096

Problem Description Given two sequences of numbers : a[1], a[2], …… , a[N], and b[1], b[2], …… , b[M] (1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make a[K] = b[1], a[K + 1] = b[2], …… , a[K + M – 1] = b[M]. If there are more than one K exist, output the smallest one.

 

Input The first line of input is a number T which indicate the number of cases. Each case contains three lines. The first line is two numbers N and M (1 <= M <= 10000, 1 <= N <= 1000000). The second line contains N integers which indicate a[1], a[2], …… , a[N]. The third line contains M integers which indicate b[1], b[2], …… , b[M]. All integers are in the range of [-1000000, 1000000].

 

Output For each test case, you should output one line which only contain K described above. If no such K exists, output -1 instead.

 

Sample Input

2 13 5 1 2 1 2 3 1 2 3 1 3 2 1 2 1 2 3 1 3 13 5 1 2 1 2 3 1 2 3 1 3 2 1 2 1 2 3 2 1  

Sample Output

6 -1  

Source
HDU 2007-Spring Programming Contest  

题意:裸的模式匹配问题,N值较大,必须使用线性算法,考虑上KMP。

关于KMP:

好久之前就看过KMP不过一直没搞懂,最近就要比赛,所以临时补一补,翻看了严蔚敏老师的数据结构,研究了许久,算是对KMP略知一二了吧,其KMP主算法还是比较好理解来的(不回溯主串匹配指针,当失配时,利用已经匹配的部分串的信息,使模式串指针向前移动,然后继续匹配),关键在于NEXT数组的求法,其实也不算很难理解(一个递推关系+自匹配的过程),书上后面说的那个修正NEXT数组的求法也比较好理解(当P[i]=P[Next[i]]时,此次滑动的没有作用的,所以直接滑到下一次去)。

#include <iostream>
#include<cstdio>
#include<cstring>
#define _match(a,b) ((a)==(b))
using namespace std;

int M[10005];
int N[1000005];
int Mlength;
int Nlength;
int T;

int kmp(int ls,int* str,int lp,int* pat)
{
    int fail[10005]={-1};
    int i=0,j;
    for(j=1;j<lp;j++)
    {
        for(i = fail[j-1]; i>=0 && !_match(pat[i+1],pat[j]); i =fail[i]);
        fail[j] = (_match(pat[i+1],pat[j])?i+1:-1);
    }
    for(i=j=0;i<ls&&j<lp;i++)
        if(_match(str[i],pat[j]))
            j++;
        else if (j)
            j = fail[j-1]+1,i--;
    return j == lp?(i-lp+1):-1;
}

int main()
{
    cin>>T;
    while(T--)
    {
        cin>>Nlength>>Mlength;
        for(int i = 0; i<Nlength; i++)
            scanf("%d",&N[i]);
        for(int i = 0; i<Mlength; i++)
            scanf("%d",&M[i]);
        int temp =kmp(Nlength,N,Mlength,M);
        cout<<temp<<endl;
    }
    return 0;
}
    原文作者:KMP算法
    原文地址: https://blog.csdn.net/tlonline/article/details/46358865
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞