写了几道题:
感觉这周任务有些难
next数组的代码实在有一些难以理解(什么流程还是知道),不过还好代码就短短几行,可以记住
P3375 【模板】KMP - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include <bits/stdc++.h>
using namespace std;
int slen,tlen;
int next1[1000010];
char s[1000005];
char t[1000005];
void Next(string t)
{
int i=-1,j=0;
next1[0]=-1;
while(j<tlen)
{
if(i==-1||t[i]==t[j])
{
next1[++j]=++i;
}
else
{
i=next1[i];
}
}
}
void kmp(string s,string t)
{
int i=0,j=0;
slen=s.size();
tlen=t.size();
Next(t);
while(i<slen)
{
if(j==-1||s[i]==t[j])
{
i++;
j++;
}
else
{
j=next1[j];
}
if(j==tlen)
{
printf("%d\n",i-tlen+1);
j=next1[j];
}
}
}
int main()
{
scanf("%s",s);
scanf("%s",t);
kmp(s,t);
for(int i=1;i<=tlen;i++)
{
printf("%d ",next1[i]);
}
return 0;
}
P4391 [BOI2009] Radio Transmission 无线传输 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
这题我看了很久都不知道结论怎么来的,只好记了
#include<bits/stdc++.h>
using namespace std;
int next1[1000005];
char s[1000005];
int l;
int len;
void funnext()
{
int i=-1,j=0;
next1[0]=-1;
while(j<len)
{
if(i==-1||s[i]==s[j])
{
next1[++j]=++i;
}
else
{
i=next1[i];
}
}
}
int main()
{
scanf("%d",&l);
scanf("%s",s);
len=strlen(s);
funnext();
printf("%d",l-next1[l]);
return 0;
}