首页 > 其他 > 详细

POJ 3461

时间:2018-10-04 03:24:55      阅读:127      评论:0      收藏:0      [点我收藏+]

第一道KMP

以后这个就作为模版了

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read(){
	int x=0,f=1,ch=getchar();
	while(ch<‘0‘||ch>‘9‘){if(ch==‘-‘)f=-1;ch=getchar();}
	while(ch>=‘0‘&&ch<=‘9‘){x=x*10+ch-‘0‘;ch=getchar();}
	return x*f;
}
char word[10005];
int len1;
int nxt[10005];
inline void pre(){
	nxt[0]=-1;
	int j=0,k=-1;
	while(j<len1){
		// puts("X");
		if(k==-1||word[k]==word[j]) nxt[++j]=++k;
		else k=nxt[k];
	}
}
char text[1000005];
int len2;
inline int kmp(){
	int i=0,j=0,res=0;
	while(i<len2){
		if(j==-1||text[i]==word[j]) ++i,++j;
		else j=nxt[j];
		if(j==len1) res++,j=nxt[j];
	}
	return res;
}
int main(){
	int T=read();
	while(T--){
		scanf("%s",word);len1=strlen(word);
		scanf("%s",text);len2=strlen(text);
		pre();
		printf("%d\n",kmp());
	}
	return 0;
}

  

POJ 3461

原文:https://www.cnblogs.com/gcyyzf/p/9740918.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!