[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
 

题意:裸的模式匹配问题,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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值