Number Sequence(KMP)

题目描述:

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.

输入:

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].

输出:

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

样例输入:

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

样例输出:

6

-1

KMP模板题。

#include<stdio.h>
#include<algorithm>
#include<stdlib.h>
#include<malloc.h>
#include<math.h>
#include<string>
#include<queue>
#include<stack>
#include<cstring>
#include<vector>
#define inf 0x3f3f3f3f
#define MAXN 1000000+10
#define LL long long
#define MAX 1000000007
#define pi 3.1415926
using namespace std;
int a[MAXN],b[MAXN],next1[MAXN];
int n,m;
void next_cal(int len)
{
    next1[0]=-1;
    int k=-1;
    for(int q=1;q<=len-1;q++)
    {
        while(k>-1&&b[k+1]!=b[q])
            k=next1[k];
        if(b[k+1]==b[q])
            k+=1;
        next1[q]=k;
    }
}
int KMP()
{
    next_cal(m);
    int k=-1;
    for(int i=0;i<n;i++)
    {
        while(k>-1&&b[k+1]!=a[i])
        {
            k=next1[k];
        }
        if(b[k+1]==a[i])
            k+=1;
        if(k==m-1)
            return i-m+1;
    }
    return -1;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        memset(next1,-1,sizeof(next1));
        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]);
        int ans=KMP();
        if(ans!=-1)
            printf("%d\n",ans+1);
        else
            printf("-1\n");
    }
    return 0;
}
附上一个讲的比较好的博客: 点击打开链接

猜你喜欢

转载自blog.csdn.net/qwerqwee12/article/details/79326043