码迷,mamicode.com
首页 > 其他好文 > 详细

KMP入门(匹配)

时间:2016-08-06 00:16:42      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:

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



解题思路:题目大意:判断第一个串中是否存在第二个串,存在则输出最小的匹配起始位置,不存在则输出-1。
利用fail数组,KMP.


#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

int N[1000005],M[10005],fail[10005];
int n,m;
void KMP();

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;i++)
        scanf("%d",&N[i]);
        for(int i=1;i<=m;i++)
        scanf("%d",&M[i]);
        KMP();
    }
    return 0;
}

void KMP()
{
    memset(fail,0,sizeof(fail));
    fail[0]=-1;//初始化fail数组
    for(int i=1;i<=m;i++)
    {
        int p=fail[i-1];
        //如果不满足要求则一直fail直到p=0
        while(p>=0&&M[p+1]!=M[i])
        p=fail[p];
        fail[i]=p+1;
    }
    int ans=0;
    for(int i=1,p=0;i<=n;i++)
    {
        while(p>=0&&M[p+1]!=N[i])
        p=fail[p];
        if(++p==m)
        {
            ans=i-m+1;
            p=fail[p];
            break;
        }
    }
     if(ans) printf("%d\n",ans);
     else printf("-1\n");
}

 



KMP入门(匹配)

标签:

原文地址:http://www.cnblogs.com/hr974041087/p/5742970.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!