您的位置:首页 > 其它

hdu 1686(Oulipo) KMP基础题 / hdu 2087(剪花布条)KMP基本运用

2013-04-26 11:48 483 查看
题目太长自己叙述吧!

原题链接地址:http://acm.hdu.edu.cn/showproblem.php?pid=1686

输入:t代表测试实例

第一行:模式串

第二行:匹配串

问模式串在匹配串中出现的次数。

3
BAPC
BAPC
AZA
AZAZAZA
VERDI
AVERDXIVYERDIAN

上面的三个实例的输出分别为:1 3 0

KMP算法看了有半天了吧!很朦胧啊!就霸王硬上弓了,套着模板A了这一题!

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define N 1000006
#define M 10004
char a[M];
char b
;
int next[M];
int n,m;
void Get_next()
{
int i=0,j=-1;
next[0]=-1;
while(i<m)
{
if(j==-1||a[i]==a[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int KMP()
{
int i=0,j=0;
int ans=0;
Get_next();
while(i<n&&j<m)
{
if(j==-1||b[i]==a[j])
{
i++;
j++;
}
else
j=next[j];
if(j==m)
ans++,j=next[j];
}
return ans;
}
int main()
{
int t;
cin>>t;
while(t--)
{
memset(next,-1,sizeof(next));
cin>>a;
m=strlen(a);
cin>>b;
n=strlen(b);
cout<<KMP()<<endl;
}
return 0;
}


hdu 2087 (剪花布条)KMP的基本运用

唯一需要注意的就是当模式串查找到后,j要回到0;

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define N 1005
char str
,s
;
int next
;
int num;
void get_next()
{

int i=0,j=-1;
next[0]=-1;
int len=strlen(s);
while(i<len)
{

if(j==-1||s[i]==s[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
void KMP()
{

int i=0,j=0;
int len=strlen(str);
int len2=strlen(s);
while(i<len)
{
if(j==len2)
{
num++;
j=0;
}
if(j==-1||str[i]==s[j])
{
i++;
j++;

}
else
j=next[j];

}
if(j==len2)
num++;
}
int main()
{

while(scanf("%s",str)!=EOF)
{

if(str[0]=='#')  break;
scanf("%s",s);
get_next();
num=0;
KMP();
printf("%d\n",num);

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: