zoukankan      html  css  js  c++  java
  • A

    Given two sequences of numbers : a11, a22, ...... , aNN, and b11, b22, ...... , bMM(1 <= M <= 10000, 1 <= N <= 1000000). Your task is to find a number K which make aKK = b11, aK+1K+1 = b22, ...... , aK+M1K+M−1 = bMM. If there are more than one K exist, output the smallest one. 

    InputThe 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 a11, a22, ...... , aNN. The third line contains M integers which indicate b11, b22, ...... , bMM. All integers are in the range of 1000000,1000000−1000000,1000000. 
    OutputFor 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
    #include<iostream>
    #include<algorithm>
    #include<cstdio>
    #include<vector>
    #include<string>
    #include<cstring>
    using namespace std;
    #define MAXN 1000001
    typedef long long LL;
    /*
    KMP  查找子串首次出现的位置
    */
    int s[MAXN],t[MAXN],Next[MAXN];
    void kmp_pre(int m)
    {
        int j,k;
        j=0;k=-1;Next[0]=-1;
        while(j<m)
        {
            if(k==-1||t[j]==t[k])
                Next[++j] = ++k;
            else
                k = Next[k];
        }
    }
    int KMP(int n,int m)
    {
        int i,j,ans;
        i=j=ans=0;
        kmp_pre(m);
        if(n==1&&m==1)
            return (s[0]==t[0])?1:-1;
        for(i=0;i<n;i++)
        {
            while(j>0&&s[i]!=t[j])
                j = Next[j];
            if(s[i]==t[j])
                j++;
            if(j>=m)
            {
                if(i-m+2>0)
                    return i-m+2;
                else
                    return -1;
            }
        }
        return -1;
    }
    int main()
    {
        int T,n,m;
        scanf("%d",&T);
        while(T--)
        {
            scanf("%d%d",&n,&m);
            for(int i=0;i<n;i++)
                scanf("%d",&s[i]);
            for(int i=0;i<m;i++)
                scanf("%d",&t[i]);
            printf("%d
    ",KMP(n,m));
        }
    }
     
  • 相关阅读:
    多线程之线程同步中的锁定lock、Monitor(转)
    信号同步
    窗体间传值的最佳方式
    Semaphore的理解
    推荐算法相关
    基于Spark的GBDT + LR模型实现
    基于Spark和Tensorflow构建DCN模型进行CTR预测
    神经网络(未完)
    互联网金融借款违约预测
    Python3基础复习
  • 原文地址:https://www.cnblogs.com/joeylee97/p/6670679.html
Copyright © 2011-2022 走看看