• HDU 1711 Number Sequence


    http://acm.hdu.edu.cn/showproblem.php?pid=1711

    Problem Description
    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.
     
    Input
    The 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].
     
    Output
    For 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

    代码:

    /*
    pku3461(Oulipo), hdu1711(Number Sequence)
    这个模板 字符串是从0开始的
    Next数组是从1开始的
    
    
    */
    
    #include <iostream>
    #include <stdio.h>
    #include <string.h>
    #include <algorithm>
    #include <math.h>
    using namespace std;
    
    const int maxn = 2e7 + 5;
    int N, M;
    int nx[maxn];
    int a[maxn], b[maxn];
    
    void getNext()
    {
        int j, k;
        j = 0; k = -1; nx[0] = -1;
        while(j < M)
            if(k == -1 || b[j] == b[k])
                nx[++j] = ++k;
            else
                k = nx[k];
    
    }
    /*
    返回模式串T在主串S中首次出现的位置
    返回的位置是从0开始的。
    */
    int KMP_Index()
    {
        int i = 0, j = 0;
        getNext();
    
        while(i < N && j < M)
        {
            if(j == -1 || a[i] == b[j])
            {
                i++; j++;
            }
            else
                j = nx[j];
        }
        if(j == M)
            return i - M + 1;
        else
            return -1;
    }
    
    int main()
    {
        int TT;
        cin>>TT;
        while(TT--)
        {
            scanf("%d%d", &N, &M);
            for(int i = 0; i < N; i ++)
                scanf("%d", &a[i]);
            for(int i = 0; i < M; i ++)
                scanf("%d", &b[i]);
    
            int ans = KMP_Index();
            printf("%d
    ", ans);
        }
        return 0;
    }
    /*
    test case
    aaaaaa a
    abcd d
    aabaa b
    */
    

      对着 kuangbin 的 KMP 模板写下来的题目!板子里的 next 数组改成了 nx 一直报 CE 让我一度怀疑是不是智商不行 按着板子写都会写错 QAQ 

  • 相关阅读:
    asp .net 页面回车触发button 按钮事件
    Asp.netPost&Get转
    2012.8.16近期总结,1模态窗口回传重新被弹出2,清空缓存 3,
    面试感言
    2012.6.27近期总结,1.sql字符串转换(cast,CONVERT )调用wcf服务,关闭模态窗口刷新付页面
    self
    空指针
    枚举和结构体
    typedef
    指针
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10606345.html
Copyright © 2020-2023  润新知