hdu 1686 Oulipo

kmp的题,这题比较简单。题意大概是,在一个串中找另一个串出现的次数。下面是我ac之后的代码,时间比较长了点,78ms。

ac代码:

View Code
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>
#include <math.h>
#include <vector>
#include <queue>
#include <stack>

using namespace std;

const int maxp=10001;
const int maxt=1000001;

char p[maxp],t[maxt];
int lenp,lent,nextval[maxp];

void get_nextval()
{
    int i,j;
    nextval[0]=-1;
    i=0,j=-1;
    while(i<lenp)
    {
        if(j==-1||p[i]==p[j])
        {
            i++;
            j++;
            if(p[i]!=p[j]) nextval[i]=j;
            else nextval[i]=nextval[j];
        }
        else j=nextval[j];
    }
}

int match()
{
    int cnt=0;
    int pp,tt;
    pp=tt=0;
    while(tt<lent)
    {
        if(p[pp]==t[tt])
        {
            pp++;
            tt++;
        }
        else if(pp>=0)
            pp=nextval[pp];
        else
        {
            tt++;
            pp=0;
        }
        if(pp==lenp)
        {
            cnt++;
            pp=nextval[pp];
        }
    }
    return cnt;
}

int main()
{
    int ncas;
    scanf("%d",&ncas);
    while(ncas--)
    {
        scanf("%s%s",p,t);
        lenp=strlen(p);
        lent=strlen(t);
        get_nextval();
        printf("%d\n",match());
    }
    return 0;
}

如果大家有什么好的思路或者可以缩减时间的措施都请回复我。谢谢!

转载于:https://www.cnblogs.com/RainingDays/archive/2012/11/12/2766453.html

猜你喜欢

转载自blog.csdn.net/weixin_33979745/article/details/94538718