hdu 1711 Number Sequence

点击此处即可传送到hdu 1711

                     **Number Sequence**


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

题目大意:首先给你一个数t,表示有t组数据,然后给你两个数,m和n,分别表示目标串S和匹配串P的个数,然后就分别有m个数和n个数,找P首先匹配成功的第一个数的下标:比如说
13 5
1 2 1 2 3 1 2 3 1 3 2 1 2
1 2 3 1 3
当i == 6的时候就匹配成功了,如果找不到就输出-1;

解题思路:KMP算法,关键是找next数组的值,KMP算法的思想就是:在匹配过程称,若发生不匹配的情况,如果next[j] >= 0,则目标串的指针i不变,将模式串的指针j移动到next[j]的位置继续进行匹配;若next[j]=-1,则将i右移1位,并将j置0,继续进行比较。
下面给出例子:
 P a b a b a

 j 0 1 2 3 4

next[j] -1 0 0 1 2
现在上代码:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

int m,n;
/*int BF(char *s, char *p)//这个是暴力做的,当然不提倡,但是可以参考(字符串的,嘿嘿,我没改) { int i,j; i = 0; while(i < strlen(s)) { j = 0; while(s[i]==p[j] && j<strlen(p)) { i++; j++; } if(j == strlen(p)) return i - strlen(p); i = i-j+1; // i 回溯 } return -1; }*/
void Getnext(int *p, int *next)//关键是这个
{
    int j = 0;
    int k = -1;
    next[0] = -1;
    while(j < n)
    {
        if(k==-1 || p[j]==p[k])
        {
            j++;
            k++;
            next[j] = k;
        }
        else
            k = next[k];
    }
}

int KMP(int *s, int *p)
{
    int next[10010];
    int i = 0;
    int j = 0;
    Getnext(p, next);
    while(i < m)
    {
        if(j==-1 || s[i]==p[j])
        {
            i++;
            j++;
        }
        else
            j = next[j];
        if(j == n)
            return i - n + 1;
    }
    return -1;
}
int s[1000000+5],p[1000000+5];
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&m,&n);
        for(int i=0; i<m; i++)
            scanf("%d",&s[i]);
        for(int i=0; i<n; i++)
            scanf("%d",&p[i]);
        printf("%d\n",KMP(s,p));
    }
    return 0;
}

你可能感兴趣的:(KMP)