您的位置:首页 > 其它

HDU 2087 剪花布条

2017-03-31 18:22 381 查看
传送门:http://acm.hdu.edu.cn/showproblem.php?pid=2087





解题思路:

简单的kmp算法

实现代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int MAXN=1010;

void makeNext(const char P[],int next[]){
int m=strlen(P);
int k;
memset(next,0,sizeof(next));
for(int i=1,k=0;i<m;i++){
if(k>0&&P[k]!=P[i])
k=next[k-1];

if(P[k]==P[i])
k++;
next[i]=k;
}
}

int kmp(const char T[],const char P[],int next[]){
int ans=0;
makeNext(P,next);
int m=strlen(P);
int n=strlen(T);
for(int i=0,k=0;i<n;i++){
if(k>0&&P[k]!=T[i])
k=next[k-1];

if(P[k]==T[i])
k++;
if(k==m){
ans++;
k=0;
}
}
return ans;
}

int main(){
char T[MAXN];
char P[MAXN];
int next[MAXN];
while(scanf("%s",T)!=EOF){
if(T[0]=='#') break;
scanf("%s",P);
cout<<kmp(T,P,next)<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: