链接
题解
在做这个题的时候可以想到用多项式乘法做字符串匹配的时候用到的一种套路:每种颜色分别做
我把每两种颜色分别拿出来然后用kmp匹配,这个预处理是 O ( k 2 n ) O(k^2n) O(k2n)的
然后,在具体匹配的时候,我找到每种颜色在模式串中的第一次出现位置,并且和匹配串对应位置上的那个颜色建立映射,然后我就得到了一个颜色对应表,这个时候就拿刚才预处理的结果看看是不是每种颜色都匹配上了,如果每种颜色都匹配上了那就ok
其实做完了之后发现还有一种更简单的方法,就是我确定了颜色的对应关系之后,直接上kmp匹配就行了
代码
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define iinf 0x3f3f3f3f
#define linf (1ll<<60)
#define eps 1e-8
#define maxn 200010
#define cl(x) memset(x,0,sizeof(x))
#define rep(i,a,b) for(i=a;i<=b;i++)
#define drep(i,a,b) for(i=a;i>=b;i--)
#define em(x) emplace(x)
#define emb(x) emplace_back(x)
#define emf(x) emplace_front(x)
#define fi first
#define se second
#define de(x) cerr<<#x<<" = "<<x<<endl
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
ll read(ll x=0)
{
ll c, f(1);
for(c=getchar();!isdigit(c);c=getchar())if(c=='-')f=-f;
for(;isdigit(c);c=getchar())x=x*10+c-0x30;
return f*x;
}
struct KMP
{
int n, next[maxn], t[maxn];
void build(char *r, int len)
{
int i, j=0;
n=len;
for(i=1;i<=len;i++)t[i]=r[i]; t[len+1]=0;
for(i=2;i<=len;i++)
{
for(;j and t[j+1]!=t[i];j=next[j]);
next[i] = t[j+1]==t[i]?++j:0;
}
}
int move(int pos, int x)
{
for(;pos and t[pos+1]!=x;pos=next[pos]);
return t[pos+1]==x ? pos+1 : 0;
}
}kmp;
int mxlen[11][11][maxn], a[maxn], b[maxn], pos[11];
char s[maxn], t[maxn];
int main()
{
int n=read(), k=read(), m, i, j, l;
rep(i,1,n)a[i]=read();
m=read();
rep(i,1,m)b[i]=read();
memset(pos,-1,sizeof(pos));
rep(i,1,m)pos[b[i]]=i;
rep(i,0,k-1)rep(j,0,k-1)
{
rep(l,1,m)s[l] = ( b[l] == j ? '*' : '_' );
rep(l,1,n)t[l] = ( a[l] == i ? '*' : '_' );
kmp.build(s,n);
rep(l,1,n)mxlen[i][j][l] = kmp.move(mxlen[i][j][l-1],t[l]);
}
int ans=0;
rep(i,1,n-m+1)
{
bool flag=true;
rep(j,0,k-1)
{
if(pos[j]!=-1)
{
if(mxlen[a[i+pos[j]-1]][j][i+m-1]!=m)
flag = false;
}
}
ans += flag;
}
printf("%d",ans);
return 0;
}