• Number Sequence HDU


    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
     1 #include<iostream>
     2 #include<cstring>
     3 #include<string>
     4 #include<cstdio>
     5 using namespace std;
     6 
     7 int nxt[1000005],s[1000005],p[10005]; 
     8 int T,n,m;
     9 
    10 void getNext(){
    11     nxt[0]=-1;
    12     for(int i=0;i<m;i++){
    13         int k=nxt[i];
    14         while(k!=-1&&p[i]!=p[k]) k=nxt[k];
    15         nxt[i+1]=k+1;
    16     }
    17 }
    18 
    19 int kmp(){
    20     getNext();
    21     int i=0,j=0;
    22     while(i<n&&j<m){
    23         while(j!=-1&&s[i]!=p[j]) j=nxt[j];
    24         ++i;
    25         ++j;   
    26     }
    27     if(j==m) return i-j+1;
    28     return -1;
    29 }
    30 
    31 int main()
    32 {   scanf("%d",&T);
    33     while(T--){
    34         scanf("%d%d",&n,&m);
    35         for(int i=0;i<n;i++) scanf("%d",&s[i]);
    36         for(int i=0;i<m;i++) scanf("%d",&p[i]);
    37         int ans=kmp();
    38         printf("%d
    ",ans);
    39     }
    40     return 0;
    41 }
  • 相关阅读:
    CSS cursor 属性笔记
    sql 不等于 <>
    去掉时间中的时分秒
    ref 和 out区别
    关于闭包(未完待续)
    面向对象——多态(摘)
    SQL Service 数据库 基本操作 视图 触发器 游标 存储过程
    遍历winform 页面上所有的textbox控价并赋值string.Empty
    关于Html 和Xml 区别(备忘)
    python之面向对象进阶
  • 原文地址:https://www.cnblogs.com/zgglj-com/p/6842842.html
Copyright © 2020-2023  润新知