• HDU1171题解——KMP模板题


    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1711

    Number Sequence

    Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
    Total Submission(s): 54826    Accepted Submission(s): 21988


    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
     
    Source
     
    Recommend
    lcy
     
    题目意思:就是首先输入t表示要处理数据的组数,然后输入n和m,后面跟着两个长度为n和m的数组。找到长度为m的数组在长度为n数组里面的出现位置(位置要最小)。
    题目思路:只需要在输入的地方稍微处理一下(原先的字符串输入改为数字输入)就行,然后直接kmp。
    ac代码:
    #include<stdio.h>
    #include<string>
    const int maxn=1e6+10;
    const int maxm=1e4+10;
    int t,n,m,s[maxn],p[maxn];
    int next[maxm];
    void GetNext()
    {
        int plen=0;
        int slen=-1;
        next[0]=-1;
        while(plen<m)
        {
            if(slen==-1||p[plen]==p[slen])
            {
                plen++;slen++;
                if(p[plen]!=p[slen])next[plen]=slen;
                else next[plen]=next[slen];
            }
            else slen=next[slen];
        }
    }
    int kmp()
    {
        int plen=0;
        int slen=0;
        while(plen<m&&slen<n)
        {
            if(plen==-1||p[plen]==s[slen])
            {
                plen++;slen++;
            }
            else plen=next[plen];
        }
        if(plen==m)
        return slen-plen+1;
        else return -1;
    }
    int main()
    {
        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",&p[i]);
            GetNext();
            printf("%d
    ",kmp());
        }
        return 0;
    }
  • 相关阅读:
    NOIP 模拟 $94; m 超级加倍$
    NOIP 模拟 $94; m 欢乐豆$
    NOIP 模拟 $94; m 叁仟柒佰万$
    NOIP 模拟 $94; m 开挂$
    NOIP 模拟 $92; m 优美的旋律$
    NOIP 模拟 $92; m 翻转游戏$
    NOIP 模拟 $92; m 石子合并$
    NOIP 模拟 $90; m 校门外歪脖树上的鸽子$
    NOIP 模拟 $90; m 混乱邪恶$
    NOIP 模拟 $90; m 快速排序$
  • 原文地址:https://www.cnblogs.com/Mingusu/p/11823970.html
Copyright © 2020-2023  润新知