题目:我是超链接
题解:
正解是KMP但是可以用hash水过去?
原来用hash判重还有这种操作。。。新姿势?
代码:
hash
#include <cstdio>
#include <iostream>
#define N 200005
using namespace std;
const int jz=31;
typedef unsigned long long ull;
ull po[N],ca[N],cb[N];
int f[N];
char A[N],B[N];
int main()
{
int n,m,k,i;
scanf("%d%d%d\n",&n,&m,&k);
gets(A+1); scanf("\n"); gets(B+1);
po[0]=1;
for (i=1;i<=200000;i++) po[i]=po[i-1]*jz;
for (i=1;i<=n;i++) ca[i]=ca[i-1]*jz+A[i];
for (i=1;i<=m;i++) cb[i]=cb[i-1]*jz+B[i];
for (i=1;i<=n;i++)
{
int l=0,r=min(m,n-i+1),tt=0;
while (l<=r)
{
int mid=(l+r)>>1;
if (ca[i+mid-1]-ca[i-1]*po[mid]==cb[mid]) tt=mid,l=mid+1;
else r=mid-1;
}
f[tt]++;
}
while (k--){int x;scanf("%d",&x); printf("%d\n",f[x]);}
}
KMP,
详细的解法,特别有益
#include <cstdio>
#include <iostream>
#include <cstring>
#define N 200005
using namespace std;
int n,m,k,t[N],ans[N];
char s1[N],s2[N];
int main()
{
scanf("%d%d%d",&n,&m,&k);
scanf("%s%s",s1,s2);
int l1=strlen(s1),l2=strlen(s2);
int j=0,i;
t[0]=-1;
for (i=0;i<l2;i++)
{
j=t[i];
while (j!=-1 && s2[i]!=s2[j]) j=t[j];
t[i+1]=++j;
}
j=0;
for (i=0;i<l1;i++)
{
while (j!=-1 && s1[i]!=s2[j]) j=t[j];
j++;
ans[j]++;
}
for (i=m;i>=1;i--) ans[t[i]]+=ans[i];
int x;
while (k--) scanf("%d",&x),printf("%d\n",ans[x]-ans[x+1]);
}