zoukankan      html  css  js  c++  java
  • hdu1711Number 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
     
    Source
    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<cmath>
    
    using namespace std;
    
    int an[1100000];
    int bn[1100000];
    int nextt[1100000];
    int match[1100000];
    
    int main()
    {
        int z,n,m,i,j,k;
        cin>>z;
        while(z--)
        {
            scanf("%d%d",&n,&m);
            for(i = 1;i<=n;i++)
                scanf("%d",&an[i]);
            for(i = 1;i<=m;i++)
                scanf("%d",&bn[i]);
            nextt[1] = 0;
            for(i = 2;i<=m;i++)
            {
                int t = nextt[i-1];
                while(t&&bn[i]!=bn[t+1]) t = nextt[t];
                if(bn[i] == bn[t+1]) t++;
                nextt[i] = t;
            }
            match[0] = 0;
            bool b = 0;
            for(i = 1;i<=n;i++)
            {
                int t = match[i-1];
                while(t&&an[i] != bn[t+1]) t = nextt[t];
                if(an[i] == bn[t+1]) t++;
                match[i] = t;
                if(t == m)
                {
                    cout<<i-m+1<<endl;
                    b = 1;
                    break;
                }
            }
            if(!b) cout<<-1<<endl;
        }
        return 0;
    }
  • 相关阅读:
    D. Constructing the Array
    B. Navigation System
    B. Dreamoon Likes Sequences
    A. Linova and Kingdom
    G. Special Permutation
    B. Xenia and Colorful Gems
    Firetrucks Are Red
    java getInstance()的使用
    java 静态代理和动态代理
    java 类加载机制和反射机制
  • 原文地址:https://www.cnblogs.com/wos1239/p/4398462.html
Copyright © 2011-2022 走看看