思路 :我们给每个数字
i
i
i分配两个64位的随机数,构成一个128位的随机串
s
t
i
st_i
sti。
那这样一个长度为
k
k
k的子排列的区间
h
a
s
h
hash
hash的异或和就等于
⊕
i
=
1
k
s
t
[
i
]
\oplus_{i=1}^kst[i]
⊕i=1kst[i]
因为1必须被包含进去,那我们以1为左端点l,枚举右端点r,设
max
l
r
=
k
\max_l^r=k
maxlr=k,那么就check一下
[
r
−
k
+
1
,
r
]
[r-k+1,r]
[r−k+1,r]是否为一个子排列。
再倒着做一遍,正确性显然。
特判一下1一个1的情况。
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 3e5 + 10;
#define fi first
#define se second
#define pb push_back
#define wzh(x) cerr<<#x<<'='<<x<<endl;
mt19937_64 mt(chrono::high_resolution_clock::now().time_since_epoch().count());
int n,a[N];
pair<LL,LL>hs[N],sum[N],st[N];
pair<LL,LL> operator ^ (const pair<LL,LL> x,const pair<LL,LL>y){
return make_pair(x.fi^y.fi,x.se^y.se);
}
int main() {
ios::sync_with_stdio(false);
cin>>n;
for(int i=1;i<=n;i++){
st[i].fi=mt();
st[i].se=mt();
}
for(int i=1;i<=n;i++)cin>>a[i];
auto cal= [&](int x){
int res=0;
int mx=a[x++];
while(x<=n&&a[x]!=1){
mx=max(mx,a[x]);
if((sum[x]^sum[x-mx])==hs[mx])res++;
x++;
}
return res;
};
int ans=0;
for(int x=1;x<=2;x++){
for(int i=1;i<=n;i++){
hs[i]=hs[i-1]^st[i];
sum[i]=sum[i-1]^st[a[i]];
}
for(int i=1;i<=n;i++){
if(a[i]==1){
ans+=cal(i)+(x==1);
}
}
reverse(a+1,a+1+n);
}
cout<<ans<<'\n';
return 0;
}