• 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
    ",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;
    }
  • 相关阅读:
    Python3 文件
    Python 字典
    Python OS
    Python函数zip-map
    Python 3.5 filter
    python3.5.2库getpass
    JavaScript学习四
    cocos creator学习
    JavaScript学习三
    JavaScript学习3
  • 原文地址:https://www.cnblogs.com/keshuqi/p/6194068.html
Copyright © 2020-2023  润新知