zoukankan      html  css  js  c++  java
  • HDU1711-----Number Sequence-----裸的KMP

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

    题目意思:

    找出b在a中的起始位置,没有则是-1

    解题思路:

    裸的KMP,不多说

    不会KMP的话可以去看http://www.cppblog.com/oosky/archive/2006/07/06/9486.html

    说的非常好

    模板我是拿的大白的

    代码:

    #include<cstdio>
    #include<cstring>
    using namespace std;
    
    const int maxn = 10000+10;
    const int maxn2 = 1000000+10;
    
    int a[maxn2];
    int b[maxn];
    
    int next[maxn];
    
    void getnext(int T[],int len,int* qnext)
    {
        qnext[0] = 0;
        qnext[1] = 0;
        for(int i=1;i<len;i++)
        {
            int j = qnext[i];
            while(j && T[i]!=T[j]) j = qnext[j];
            qnext[i+1] = (T[i]==T[j])?j+1:0;
        }
    }
    
    int KMP(int S[],int T[],int len1,int len2)
    {
        getnext(T,len2,next);
        int j=0;
        for(int i=0;i<len1;i++)
        {
            while(j && S[i]!=T[j]) j = next[j];
            if(T[j] == S[i])
                j++;
            if(j==len2)//已经找到匹配串
            {
                return i-len2+1;
            }
    
        }
        return -1;
    }
    
    int main()
    {
        int t;
        scanf("%d",&t);
        int n,m;
        while(t--)
        {
            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(a,b,n,m);
            if(ans != -1)
                printf("%d
    ",ans+1);
            else
                printf("-1
    ");
        }
        return 0;
    }
    
    


  • 相关阅读:
    [HNOI2008] Cards
    loj #136
    a problem
    dp * 3
    STL
    套题1
    luogu 4211
    loj #2319
    loj #2316
    luogu 1144
  • 原文地址:https://www.cnblogs.com/pangblog/p/3257867.html
Copyright © 2011-2022 走看看