Codeforces 689D Friends and Subsequences

链接

传送门

题意

给出序列a和序列b,问有多少组l、r满足\(\max \limits_{i=l}^{r}a_i=\min\limits_{i=l}^{r}b_i\)

思路

对于左端点固定的区间,最大值随右端点的单调不降,最小值单调不增。 所以\(\max \limits_{i=l}^{r}a_i-\min\limits_{i=l}^{r}b_i\)也是单调不降的。因此可以对于每个左端点二分满足条件的右端点的区间求解。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;

const int maxn = 200005;
const int maxm = 18;

int n, mm[maxn];
int Max[maxn][maxm], Min[maxn][maxm];

int rmq(int L, int R, bool x) {
int k = mm[R - L + 1];
return x ? max(Max[L][k], Max[R - (1 << k) + 1][k]) : min(Min[L][k], Min[R - (1 << k) + 1][k]);
}

int main() {
int n;
scanf("%d", &n);
mm[0] = -1;
for (int i = 1; i <= n; ++i) {
mm[i] = (i & (i - 1)) ? mm[i - 1] : mm[i - 1] + 1;
scanf("%d", &Max[i][0]);
}
for (int i = 1; i <= n; ++i) {
scanf("%d", &Min[i][0]);
}
for(int j = 1; j <= mm[n]; ++j) {
for(int i = 1; i + (1 << j) - 1 <= n; ++i) {
Max[i][j] = max(Max[i][j - 1], Max[i + (1 << (j - 1))][j - 1]);
Min[i][j] = min(Min[i][j - 1], Min[i + (1 << (j - 1))][j - 1]);
}
}
LL ans = 0;
int L, R, mid;
for (int i = 1; i <= n; ++i) {
L = i, R = n;
while (L <= R) {
mid = (L + R) >> 1;
if (rmq(i, mid, true) - rmq(i, mid, false) < 0) {
L = mid + 1;
} else {
R = mid - 1;
}
}
ans -= L;
L = i, R = n;
while (L <= R) {
mid = (L + R) >> 1;
if (rmq(i, mid, true) - rmq(i, mid, false) <= 0) {
L = mid + 1;
} else {
R = mid - 1;
}
}
ans += L;
}
printf("%lld\n", ans);
return 0;
}