HDU—1711Number Sequence

版权声明:请联系[email protected] https://blog.csdn.net/wanglin007/article/details/81836591

Number Sequence
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 40418 Accepted Submission(s): 16667

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

Source
HDU 2007-Spring Programming Contest

Recommend
lcy | We have carefully selected several similar problems for you: 1358 3336 1686 3746 1251

Statistic | Submit | Discuss | Note

Home | Top Hangzhou Dianzi University Online Judge 3.0
Copyright © 2005-2018 HDU ACM Team. All Rights Reserved.
Designer & Developer : Wang Rongtao LinLe GaoJie GanLu
Total 0.000000(s) query 5, Server time : 2018-08-19 11:36:19, Gzip enabled Administration
题解:
首先因为输入数据非常多需要节省时间故用scanf和printf为输入输出;
其次因为暴力枚举非常耗时间,故用KMP算法可以将时间复杂度降到o(n+m);
这里加上我对KMP算法的小心得网址:https://blog.csdn.net/wanglin007/article/details/81807598里面还有别人的详细介绍和说明,
这个是别人的具体说明:https://blog.csdn.net/starstar1992/article/details/54913261/

#include<iostream>
#include<cstring>
using namespace std;
//const int ma=10010;
//const int na=1000010;
//int x[ma],y[na];
void knext(int next[],int x[],int len)
{
    next[0]=-1;
    int k=-1;
    for(int i=1;i<len;i++)
    {
        while(k>-1&&x[k+1]!=x[i])k=next[k];//往前回溯 
        if(x[k+1]==x[i])k++;//如果相同则比上一个next1 
        next[i]=k;// 把相同的最大前缀和后缀长赋给此时的next 
    }
}
int kmp(int next[],int y[],int leny,int x[],int lenx)
{
    knext(next,x,lenx);
    int k=-1;
    for(int i=0;i<leny;i++)
    {
        while(k>-1&&y[i]!=x[k+1])k=next[k];
        if(y[i]==x[k+1])k++;
        if(k==lenx-1)return i-lenx+2;
    }
    return -1;
}
int main()
{
    int *x,*y,n,m,t,*next;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        next=new int[m];
        for(int i=0;i<m;i++)next[i]=0;
        x=new int[m];
        y=new int[n];
        for(int i=0;i<n;i++)scanf("%d",&y[i]);
        for(int i=0;i<m;i++)scanf("%d",&x[i]);
        printf("%d\n",kmp(next,y,n,x,m));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wanglin007/article/details/81836591