K.King of Range
题目传送门:
题面:
题目大意:
给出一个大小为
n
n
n 的序列,找出
m
a
x
−
m
i
n
>
k
m a x − m i n > k
max−min>k的区间个数。
m
m
m个询问,对于每个询问给定一个常数
k
k
k,输出区间个数。
思路:
尺取。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e7 + 9;
int a[maxn];
int up[maxn];
int down[maxn];
int main() {
int n, m, k;
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> a[i];
while (m--) {
cin >> k;
int hh = 0, tt = -1, hh1 = 0, tt1 = -1, cnt = 1;
ll ans = 0;
for (int i = 1; i <= n; i++) {
while (hh <= tt && a[up[tt]] <= a[i])tt--;
up[++tt] = i;
while (hh1 <= tt1 && a[down[tt1]] >= a[i])tt1--;
down[++tt1] = i;
while (i >= cnt && a[up[hh]] - a[down[hh1]] > k) {
ans += (n - i) + 1;
cnt++;
if (cnt > up[hh])hh++;
if (cnt > down[hh1])hh1++;
}
}
cout << ans << endl;
}
}