HDU 1711 Number Sequence(KMP模板)

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
 
KMP算法:
其核心是next数组(该数组中存放的是每个位置处的最长后缀与前缀相同的长度)。
next数组的不同值包含的意义是:
(1)next[0]= -1 意义:任何串的第一个字符的模式值规定为-1;
(2)next[i]= -1   意义:模式串T中下标为i的字符,如果与首字符相同,且i的前面的1—j个字符与开头的1—j个字符不等(或者相等但T[j]==T[i]),
  如:T=”abCabCad” 则 next[6]=-1,因T[3]=T[6];
(3)next[i]=j   意义:模式串T中下标为i的字符,如果i的前面j个字符与开头的j个字符相等,且T[i] != T[j] ,
  即T[0]T[1]T[2]。。。T[j-1]==T[i-j]T[i-j+1]T[i-j+2]…T[i-1]且T[i] != T[j];
(4)next[i]=0   意义:除(1)(2)(3)的其他情况。
 那么next数组求解代码是:
void Start()
{
    int i = 0, j = -1;
    while (i < m)
    {
        if (j == -1 || b[i] == b[j])
        {
            ++i;
            ++j;
            if (b[i] != b[j])
                next[i] = j;
            else
                next[i] = next[j];
        }
        else
            j = next[j];
    }
}

详解KMP算法网址:
(原创)详解KMP算法 - 孤~影 - 博客园 http://www.cnblogs.com/yjiyjige/p/3263858.html

#include<stdio.h>

const int N=1000010;

int a[N], b[10010], next[10010];
int m, n;

void Getnext()
{
    int i = 0, j = -1;

    while (i < m)
    {
        if (j == -1 || b[i] == b[j])
        {
            i++;
            j++;

            if (b[i] == b[j])
                next[i] = next[j];
            else next[i] = j;
        }
        else j = next[j];
    }
}

int main ()
{
    int T, i, j;

    scanf("%d", &T);

    while (T--)
    {
        scanf("%d%d", &n, &m);
        for (i = 0; i < n; i++)
            scanf("%d", &a[i]);
        for (i = 0; i < m; i++)
            scanf("%d", &b[i]);

        next[0] = -1;
        Getnext();

        i = 0; j = 0;
        while (i < n && j < m)
        {
            if (j == -1 || a[i] == b[j])
            {
                i++;
                j++;
            }
            else j = next[j];
        }

        if (j == m) printf("%d\n", i-j+1);
        else printf("-1\n");
    }

    return 0;
}
posted @ 2015-09-01 13:00  搁浅の记忆  阅读(138)  评论(0编辑  收藏  举报