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));
        }
    }
     
  • 相关阅读:
    iOS 关于使用xib创建cell的两种初始化方式
    KVO的初级使用
    通知的初级使用
    C语言的变量 常量
    C语言的编译 链接
    1 hello word
    java 中 == 与 equals引出的字符串比较
    02PSP0级及登陆界面开发
    00软工课程引言
    06动手动脑
  • 原文地址:https://www.cnblogs.com/joeylee97/p/6670679.html
Copyright © 2011-2022 走看看