HDU 1686 Oulipo
求子串在母串中出现的次数。。主要是在模板题上加54~58行的代码。
#include<iostream>
#include<algorithm>
#include<string.h>
#include<stdio.h>
using namespace std;
const int maxn = 1e6+20;
int nxt[maxn];
int m;//母
int n;//子
int ans;
char s[maxn];//母
char t[maxn];//子
void getnxt()
{
int i=1;
int j=0;
nxt[0]=0;
while(i<n)
{
if(t[j]==t[i])
{
nxt[i++]=++j;
}
else if(j==0)
{
i++;
}
else
{
j=nxt[j-1];
}
}
}
int kmp()
{
int i=0;//母
int j=0;//子
while(i<m&&j<n)
{
if(s[i]==t[j])
{
i++;
j++;
}
else if(j==0)
{
i++;
}
else
{
j=nxt[j-1];
}
if(j==n)//关键
{
ans++;
j=nxt[j-1];
}
}
return ans;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
ans=0;
scanf("%s",&t);//子串
n=strlen(t);//子串长度
scanf("%s",&s);//母串
m=strlen(s);//母串长度
getnxt();
kmp();
printf("%d\n",ans);
}
return 0;
}
HDU 2087剪花布条
求子串在母串中出现的次数 。母aaaaaa 子aa,在上一题会输出5。但在本题,由于布条被剪掉了, 输出3.
和上一题的主要区别是54~58行
#include<iostream>
#include<string.h>
#include<algorithm>
#include<stdio.h>
using namespace std;
const int maxn = 1e6+20;
int nxt[maxn];
int m;//母
int n;//子
int ans;
char s[maxn];//母串
char t[maxn];//子串
void getnxt()//next数组
{
int i=1;
int j=0;
nxt[0]=0;
while(i<m)
{
if(t[j]==t[i])//情况1
{
nxt[i++]=++j;
}
else if(!j)//情况2
{
i++;
}
else//情况3
{
j=nxt[j-1];
}
}
}
int kmp()
{
int i=0;
int j=0;
while(i<m&&j<n)
{
if(s[i]==t[j])
{
i++;
j++;
}
else if(j==0)
{
i++;
}
else
{
j=nxt[j-1];
}
if(j==n)
{
ans++;
j=0;
}
}
return ans;
}
int main()
{
while(scanf("%s",&s)!=EOF && s[0]!='#')//母串
{
ans=0;
m=strlen(s);//母串长度
scanf("%s",&t);//子串
n=strlen(t);//子串长度
getnxt();
kmp();
printf("%d\n",ans);
}
return 0;
}