zoukankan      html  css  js  c++  java
  • Number Sequence HDU

    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. 

    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 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]. 
    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 <bits/stdc++.h>
     2 using namespace std;
     3 const int maxn = 1e6 + 10;
     4 int n, m;
     5 int a[maxn];
     6 int b[maxn];
     7 int nex[maxn];
     8 
     9 void getnext()
    10 {
    11     int i = 1, j = 0;
    12     nex[1] = 0;
    13     while (i < m)
    14     {
    15         if (j == 0 || b[i] == b[j])
    16         {
    17             i++, j++;
    18             if (b[i] != b[j]) nex[i] = j;
    19             else nex[i] = nex[j];
    20         }
    21         else j = nex[j];
    22     }
    23 }
    24 
    25 int kmp()
    26 {
    27     int i, j; i = j = 1;
    28     while (i <= n && j <= m)
    29     {
    30         if (j == 0 || a[i] == b[j]) i++, j++;
    31         else j = nex[j];
    32     }
    33     if (j > m)
    34         return i - m;
    35     else return -1;
    36 }
    37 
    38 int main()
    39 {
    40     int T; cin >> T;
    41     while (T--)
    42     {
    43         cin >> n >> m;
    44         for (int i = 1; i <= n; i++)
    45             scanf("%d", a + i);
    46         for (int i = 1; i <= m; i++)
    47             scanf("%d", b + i);
    48         getnext();
    49         int res = kmp();
    50         cout << res << endl;
    51     }
    52 }
     
  • 相关阅读:
    Semaphore类
    我的java学习之路五:java的循环和条件语句
    我的java学习之路四:java的基础类型和变量
    第一节 线性表
    我的java学习之路三:java的类与对象
    我的Java学习之路二:Java基础语法
    算法分析一:基本定义
    我的java学习之路一:java的安装以及环境配置
    【2019 CCPC 江西省赛】Cotree 树重心
    【2018 icpc 南京站】G
  • 原文地址:https://www.cnblogs.com/liuwenhan/p/11445654.html
Copyright © 2011-2022 走看看