题意:给定一个排列长度为 的排列 ,问有多少子区间满足其最大值的出现位置在其最小值的出现位置的右边。
数据范围:。
套路地,考虑一次性枚举最大值为 的所有区间。
记 为 右边首个大于 的下标(不存在则为 ), 为 左边首个大于 的下标(不存在则为 )。
则最大值为 的区间,左端点 ,右端点 。
先判掉某一端点为 的情况。
然后,考虑一种暴力。直接枚举右端点 ,找出 区间上的最小值 ,然后找出 左端第一个比 小的数 ,则左端点把 囊括进去就可以了。
暴力枚举左端点也是类似的。当然这样做复杂度是错的,构造一个 ,且每次都枚举左端点就炸了。
但是如果比较左端点的可能值个数和右端点的可能值个数,并选择少的那个枚举,总复杂度就是 ,这叫做启发式分裂。
原因在于考虑每个数被枚举到的所有时刻。下一时刻的区间长度至多为上一时刻的区间长度的一半,故被枚举到的次数不超过 次。
代码:
#include <bits/stdc++.h>
int a[1000005], n;
int lmi[1000005], rmi[1000005], lma[1000005], rma[1000005];
int tp = 0, st[1000005];
long long ans = 0ll;
void wk1(int l, int x, int r){
int e = 1e9, y;
for(int i = x - 1; i >= l; --i){
if(a[i] < e){
e = a[i];
y = rmi[i];
}
ans += 1ll * std::min(y - x - 1, r - x);
}
return ;
}
void wk2(int l, int x, int r){
int e = 1e9, y;
for(int i = x + 1; i <= r; ++i){
if(a[i] < e){
e = a[i];
y = lmi[i];
}
ans += 1ll * std::max(0, y - l + 1);
}
return ;
}
int main(){
scanf("%d", &n);
for(int i = 1; i <= n; ++i) scanf("%d", &a[i]);
tp = 0; st[0] = 0;
for(int i = 1; i <= n; ++i){
while(tp && a[i] < a[st[tp]]) --tp;
lmi[i] = st[tp];
st[++tp] = i;
}
tp = 0; st[0] = 0;
for(int i = 1; i <= n; ++i){
while(tp && a[i] > a[st[tp]]) --tp;
lma[i] = st[tp];
st[++tp] = i;
}
tp = 0; st[0] = n + 1;
for(int i = n; i >= 1; --i){
while(tp && a[i] < a[st[tp]]) --tp;
rmi[i] = st[tp];
st[++tp] = i;
}
tp = 0; st[0] = n + 1;
for(int i = n; i >= 1; --i){
while(tp && a[i] > a[st[tp]]) --tp;
rma[i] = st[tp];
st[++tp] = i;
}
for(int i = 1; i <= n; ++i){
int lm = lma[i] + 1, rm = rma[i] - 1;
if(i - lm + 1 <= rm - i + 1) wk1(lm, i, rm);
else wk2(lm, i, rm);
ans += 1ll * (i - lm);
//printf("%d %d %d %lld\n", i, lm, rm, ans);
}
printf("%lld\n", ans);
return 0;
}