hdu1711(KMP入门题)

26 篇文章 0 订阅
9 篇文章 0 订阅

http://acm.hdu.edu.cn/showproblem.php?pid=1711

题意:从s串中如果能找出p串,则输出p串在s串的位置(两个串下标都从1开始)

KMP模板题。。。。

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <stack>
#include <math.h>
#include <algorithm>
using namespace std;

int s[1000010],p[10010];
int nextval[10010];
int num1,num2;
/*
5
13 10
1 2 3 1 4 5 8 7 2 1 4 7 6
1 2 1 2 3 1 2 1 2 9
-1 0 0 1 2 0 1 2 3 4 0
-1 0 -1 0 2 -1 0 -1 0 4 0
*/
void getnext(const int*p){
	int i = 0, j = -1;
	nextval[0] = -1;
	while(i != num2){
		if(j == -1 || p[i] == p[j]) nextval[++i] = ++j;
		else j = nextval[j];
	}
}

int KMP(const int *s,const int *p){
    int i=0,j=0;
    while(i!=num1&&j!=num2){
        if(s[i]!=p[j]){
            if(nextval[j]==-1) i++,j=0;
            else j=nextval[j];
        }else i++,j++;
    }//while
    if(j==num2) return i-j+1;
    return -1;
}
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&num1,&num2);
        for(int i=0;i<num1;i++) scanf("%d",&s[i]);
        for(int i=0;i<num2;i++) scanf("%d",&p[i]);
        getnext(p);
        int ans=KMP(s,p);
        printf("%d\n",ans);
    }//while
    return 0;
}

稍作优化:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <stack>
#include <math.h>
#include <algorithm>
using namespace std;

int s[1000010],p[10010];
int nextval[10010];
int num1,num2;
void getnext(const int *p){
    int i=0,j=-1;
    nextval[0]=-1;
    while(i!=num2){
        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];
    }//while
}
int KMP(const int *s,const int *p){
    int i=0,j=0;
    while(i!=num1&&j!=num2){
        if(s[i]!=p[j]){
            if(nextval[j]==-1) i++,j=0;
            else j=nextval[j];
        }else i++,j++;
    }//while
    if(j==num2) return i-j+1;
    return -1;
}
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&num1,&num2);
        for(int i=0;i<num1;i++) scanf("%d",&s[i]);
        for(int i=0;i<num2;i++) scanf("%d",&p[i]);
        getnext(p);
        int ans=KMP(s,p);
        printf("%d\n",ans);
    }//while
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值