zoukankan      html  css  js  c++  java
  • Number Sequence

    题意:给你一个a串和一个b串,问b串是否是a串的子串,如果是返回b在a中最早出现的位置,否则输出-1

     
    分析:应该是最简单的模板题了吧.....
    代码如下:
    ==============================================================================================
    #include<stdio.h>
    #include<string.h>
    
    const int MAXM = 1e4+7;
    const int MAXN = 1e6+7;
    
    int a[MAXN], b[MAXM], next_b[MAXM];
    
    void GetNext(int b[], int next[], int M)
    {
        int i=0, j=-1;
        next[0] = -1;
    
        while(i < M)
        {
            if(j==-1 || b[i]==b[j])
                next[++i] = ++j;
            else
                j = next[j];
        }
    }
    int KMP(int a[], int b[], int next[], int N, int M)
    {
        int i = 0, j = 0;
    
        while(i < N)
        {
            while(j==-1 || a[i] == b[j] && j<M)
                i++, j++;
    
            if(j == M)return i-M+1;
    
            j = next[j];
        }
    
        return -1;
    }
    
    int main()
    {
        int T;
    
        scanf("%d", &T);
    
        while(T--)
        {
            int i, N, M;
    
            scanf("%d%d", &N, &M);
    
            for(i=0; i<N; i++)
                scanf("%d", &a[i]);
            for(i=0; i<M; i++)
                scanf("%d", &b[i]);
    
            GetNext(b, next_b, M);
    
            printf("%d
    ", KMP(a, b, next_b, N, M));
        }
    
        return 0;
    }
  • 相关阅读:
    bzoj2400 Spoj 839 Optimal Marks
    01分数规划
    bzoj1565 植物大战僵尸
    bzoj1497 最大获利(最大权闭合子图)
    bzoj3144 切糕
    loj6045 价
    bzoj3894 文理分科
    luogu3731 新型城市化
    快速傅里叶变换(FFT)
    bzoj1030 文本生成器
  • 原文地址:https://www.cnblogs.com/liuxin13/p/4729376.html
Copyright © 2011-2022 走看看