• hdu 1711Number Sequence (KMP——输出模式串第一次出现位置)


    Number Sequence

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


    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
     
    KMP模板题,返回模式串第一次出现在主串中的位置
    #pragma comment(linker, "/STACK:1024000000,1024000000")
    #include<cstdio>
    #include<string>
    #include<iostream>
    #include<cstring>
    #include<cmath>
    #include<stack>
    #include<queue>
    #include<vector>
    #include<map>
    #include<stdlib.h>
    #include<algorithm>
    #define LL __int64
    using namespace std;
    const int MAXN=1000000+5;
    int S[MAXN],T[MAXN];
    int nex[MAXN];
    int n,m;
    
    void KMP_nex()
    {
        int j,k;
        j=0;k=-1,nex[0]=-1;
        while(j<m)
        {
            if(k==-1 || T[j]==T[k])
                nex[++j]=++k;
            else k=nex[k];
        }
    }
    
    int KMP_ID()
    {
        int i=0,j=0;
        KMP_nex();
    
        while(i<n && j<m)
        {
            if(j==-1 || S[i]==T[j])
                i++,j++;
            else
                j=nex[j];
        }
        if(j==m) return i-m+1;
        else return -1;
    }
    
    int main()
    {
        //freopen("in.txt","r",stdin);
        int kase;
        scanf("%d",&kase);
        while(kase--)
        {
            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",&T[i]);
            printf("%d
    ",KMP_ID());
        }
        return 0;
    }
    View Code
  • 相关阅读:
    使用Xshell为xftp开ssh通道代理
    linux下查找svn的相关目录的命令
    linux服务器A远程连接服务器B的mysql及1045错误
    怎样下载带权限认证的文件?
    Vue项目打包部署总结
    Vue项目打包压缩:让页面更快响应
    axios请求失败自动重发
    可用的后台管理系统
    vue组件间方式总结
    非脚手架创建vue项目,并使用webpack打包
  • 原文地址:https://www.cnblogs.com/clliff/p/4713337.html
Copyright © 2020-2023  润新知