HDU 1711 Number Sequence

http://acm.hdu.edu.cn/showproblem.php?pid=1711

 

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

 

代码:

/*
pku3461(Oulipo), hdu1711(Number Sequence)
这个模板 字符串是从0开始的
Next数组是从1开始的


*/

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
using namespace std;

const int maxn = 2e7 + 5;
int N, M;
int nx[maxn];
int a[maxn], b[maxn];

void getNext()
{
    int j, k;
    j = 0; k = -1; nx[0] = -1;
    while(j < M)
        if(k == -1 || b[j] == b[k])
            nx[++j] = ++k;
        else
            k = nx[k];

}
/*
返回模式串T在主串S中首次出现的位置
返回的位置是从0开始的。
*/
int KMP_Index()
{
    int i = 0, j = 0;
    getNext();

    while(i < N && j < M)
    {
        if(j == -1 || a[i] == b[j])
        {
            i++; j++;
        }
        else
            j = nx[j];
    }
    if(j == M)
        return i - M + 1;
    else
        return -1;
}

int main()
{
    int TT;
    cin>>TT;
    while(TT--)
    {
        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_Index();
        printf("%d\n", ans);
    }
    return 0;
}
/*
test case
aaaaaa a
abcd d
aabaa b
*/

  对着 kuangbin 的 KMP 模板写下来的题目!板子里的 next 数组改成了 nx 一直报 CE 让我一度怀疑是不是智商不行 按着板子写都会写错 QAQ 

posted @ 2019-03-27 11:31  丧心病狂工科女  阅读(175)  评论(0编辑  收藏  举报