Rubik is very keen on number permutations.
A permutation a with lengthn is a sequence, consisting of n different numbers from 1 to n. Element numberi (1 ≤ i ≤ n) of this permutation will be denoted asai.
Furik decided to make a present to Rubik and came up with a new problem on permutations. Furik tells Rubik two number permutations: permutationa with length n and permutationb with length m. Rubik must give an answer to the problem: how many distinct integersd exist, such that sequence c (c1 = a1 + d, c2 = a2 + d, ..., cn = an + d) of length n is a subsequence of b.
Sequence a is a subsequence of sequence b, if there are such indicesi1, i2, ..., in(1 ≤ i1 < i2 < ... < in ≤ m), thata1 = bi1,a2 = bi2,..., an = bin, wheren is the length of sequence a, and m is the length of sequenceb.
You are given permutations a and b, help Rubik solve the given problem.
The first line contains two integers n andm (1 ≤ n ≤ m ≤ 200000) — the sizes of the given permutations. The second line containsn distinct integers — permutation a, the third line contains m distinct integers — permutationb. Numbers on the lines are separated by spaces.
On a single line print the answer to the problem.
1 1 1 1
1
1 2 1 2 1
2
3 3 2 3 1 1 2 3
0
首先我们可以知道A序列是1~n的排列,那么我们可以先在B序列中把1~n的排列找出来,看其相对位置是否与A相同(hash可做),相同即表明存在一个d满足条件。
以此类推,我们接下来可以把B中 2~ n + 1的排列找出来,如果其每位-1后相对顺序还是与A序列一致,即存在d-1也满足。。。
线段树中保存一个长度为n的序列的hash。
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=200010;
const int B=10007;
int N,M,pos[maxn];
LL xp[maxn];
LL val,sum;
struct IntervalTree
{
LL hash[maxn<<2];
int cnt[maxn<<2];
void build(int o,int l,int r)
{
hash[o]=cnt[o]=0;
if(l==r)return ;
int mid=(l+r)>>1;
build(o<<1,l,mid);
build(o<<1|1,mid+1,r);
}
void pushup(int o)
{
hash[o]=hash[o<<1]*xp[cnt[o<<1|1]]+hash[o<<1|1];
cnt[o]=cnt[o<<1]+cnt[o<<1|1];
}
void update(int o,int l,int r,int pos,int val,int num)
{
if(l==r)
{
hash[o]+=num*val;
cnt[o]+=num;
return;
}
int mid=(l+r)>>1;
if(pos<=mid)update(o<<1,l,mid,pos,val,num);
else update(o<<1|1,mid+1,r,pos,val,num);
pushup(o);
}
}tree;
int main()
{
while(scanf("%d%d",&N,&M)!=EOF)
{
val=sum=0;
xp[0]=1;
for(int i=1;i<=N;i++){xp[i]=xp[i-1]*B;sum+=xp[i-1];}
for(int i=1;i<=N;i++)
{
int x;
scanf("%d",&x);
val=val*B+x;
}
for(int i=1;i<=M;i++)
{
int x;
scanf("%d",&x);
pos[x]=i;
}
tree.build(1,1,M);
int ans=0;
for(int i=1;i<=M;i++)//把数值1~M按顺序加入线段树中
{
tree.update(1,1,M,pos[i],i,1);
if(i>=N)
{
if(tree.hash[1]-(sum*(i-N))==val)
ans++;
tree.update(1,1,M,pos[i-N+1],i-N+1,-1);
}
}
printf("%d\n",ans);
}
return 0;
}