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 }
     
  • 相关阅读:
    HDU 1203 01背包变形题,(新思路)
    HDU 2955 变形较大的01背包(有意思,新思路)
    HDU 2191(多重背包转换为01背包来做)
    HDU 1114(没有变形的完全背包)
    HDU2546(01背包加一点点变形)
    HDU 1950(LIS)
    c模拟 页式管理页面置换算法之FIFO
    HDU 1257 最少拦截系统(贪心 or LIS)
    路由选择(codevs 1062)
    钓鱼(洛谷 P1717)
  • 原文地址:https://www.cnblogs.com/liuwenhan/p/11445654.html
Copyright © 2011-2022 走看看