题目:
题解:
首先我们使用单调栈来维护出,当每个点作为最左端的最大值时,其左端点和右端点最远能到达的位置。
考虑如果选定一个端点,那么可行的右端点的数量可以用树状数组查询。(查询 [l,r] [ l , r ] 中小于 x x 的数字数量可以用 中小于 x x 的数字数量减去 中小于 x x 的数字数量)
因为最大值本身会造成一个至多为 的隔断,所以每次会把数字数量分为两半,最多 log n l o g n 层。
所以考虑直接枚举数字少的那边的端点,在另一边查询小于 maxli or ri m a x l i o r r i 的数字的数量即可。时间复杂度 O(n log2n) O ( n l o g 2 n )
代码:
#include <algorithm>
#include <cstdio>
#define LL long long
using namespace std;
const int N=100005;
struct hh{int wz,z;}a[N];
struct wh{int l,r,w;}tree[N*100];
int sz,stack[N],c[N],b[N],root[N],l[N],r[N];
int cmp(hh a,hh b){return a.z>b.z;}
void insert(int &now,int l,int r,int x)
{
tree[++sz]=tree[now]; now=sz;
tree[now].w++;
if (l==r) return;
int mid=(l+r)>>1;
if (x<=mid) insert(tree[now].l,l,mid,x);
else insert(tree[now].r,mid+1,r,x);
}
LL qurry(int i,int j,int l,int r,int x)
{
if (j<i || x<1) return 0;
if (1<=l && x>=r) return tree[j].w-tree[i].w;
int mid=(l+r)>>1;LL ans=0;
if (1<=mid) ans+=qurry(tree[i].l,tree[j].l,l,mid,x);
if (x>mid) ans+=qurry(tree[i].r,tree[j].r,mid+1,r,x);
return ans;
}
int main()
{
int n,top=0;scanf("%d",&n);
for (int i=1;i<=n;i++) scanf("%d",&a[i].z),a[i].wz=i,b[i]=a[i].z,c[i]=a[i].z;
sort(b+1,b+n+1);int s=unique(b+1,b+n+1)-b-1;
for (int i=1;i<=n;i++) a[i].z=lower_bound(b+1,b+s+1,a[i].z)-b;
for (int i=1;i<=n;i++) root[i]=root[i-1],insert(root[i],1,n,a[i].z),l[i]=1,r[i]=n;
for (int i=1;i<=n;i++)
{
while (top&&a[stack[top]].z<a[i].z)
{
r[stack[top]]=i-1;
top--;
}
stack[++top]=i;
}
top=0;
for (int i=n;i>=1;i--)
{
while (top&&a[stack[top]].z<=a[i].z)
{
l[stack[top]]=i+1;
top--;
}
stack[++top]=i;
}
sort(a+1,a+n+1,cmp);
LL ans=0;
for (int i=1;i<=n;i++)
{
int wz=a[i].wz;
if (r[wz]-wz>wz-l[wz])
{
for (int j=l[wz];j<=wz;j++)
{
int lj=upper_bound(b+1,b+s+1,b[a[i].z]/c[j])-b-1;
ans+=qurry(root[wz-1],root[r[wz]],1,n,lj);
}
}else
{
for (int j=r[wz];j>=wz;j--)
{
int lj=upper_bound(b+1,b+s+1,b[a[i].z]/c[j])-b-1;
ans+=qurry(root[l[wz]-1],root[wz],1,n,lj);
}
}
}
printf("%lld",ans);
}