hdu[1711]number sequence

Posted AronQi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

Solution

kmp模版题目

#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;
inline int read(){
    int x=0,c=getchar(),f=1;
    for(;c<48||c>57;c=getchar())
        if(!(c^45))
            f=-1;
    for(;c>47&&c<58;c=getchar())
        x=(x<<1)+(x<<3)+c-48;
    return x*f;
}
int sub_l,tar_l,sub[10001],tar[1000001],p[10001];
inline void pre(){
    for(int i=2,j=0;i<=sub_l;i++){
        while(j&&sub[j+1]^sub[i])
            j=p[j];
        if(!(sub[j+1]^sub[i]))
            j++;
        p[i]=j;
    }
}
inline void kmp(){
    int ans=-1;
    for(int i=1,j=0;i<=tar_l;i++){
        while(j&&sub[j+1]^tar[i])
            j=p[j];
        if(!(sub[j+1]^tar[i]))
            j++;
        if(!(j^sub_l)){
            ans=i-sub_l+1;
            break;
        }
    }
    printf("%d\n",ans);
}
int main(){
    int T=read();
    while(T--){
        tar_l=read(),sub_l=read();
        memset(p,0,sizeof(p));
        for(int i=1;i<=tar_l;i++)
            tar[i]=read();
        for(int j=1;j<=sub_l;j++)
            sub[j]=read();
        pre(); kmp();
    }
    return 0;
}

 

以上是关于hdu[1711]number sequence的主要内容,如果未能解决你的问题,请参考以下文章

Number Sequence (HDU 1711)

HDU——T 1711 Number Sequence

Number Sequence HDU - 1711

hdu[1711]number sequence

hdu 1711 Number Sequence

HDU - 1711 Number Sequence