-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathE.cpp
78 lines (67 loc) · 1.57 KB
/
E.cpp
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <bits/stdc++.h>
using namespace std;
#ifndef LOCAL
#define cerr if(0) cerr
#endif
#define all(v) (v).begin(), (v).end()
template <class T> using vec = vector<T>;
using vll = vec<int64_t>; using vii = vec<int>;
int main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
int n; cin >> n;
vii a(n); for (auto &i : a) cin >> i;
rotate(a.begin(), max_element(all(a)), a.end());
++a[0];
a.emplace_back(a[0]);
// tired of stacks
vii l(n + 3, -1), r(n + 3, n + 2);
for (int i = 1; i < n + 1; ++i) {
int option = i - 1;
while (option >= 0 && a[option] <= a[i]) {
option = l[option];
}
l[i] = option;
}
for (int i = n; i >= 0; --i) {
int option = i + 1;
while (option < n + 1 && a[option] <= a[i]) {
option = r[option];
}
r[i] = option;
}
// the boss bitch
vll fen(n + 4);
auto update = [&](int idx, int64_t v) {
for (++idx; idx < n + 4; idx += idx & -idx) {
fen[idx] += v;
}
};
auto sum = [&](int idx) {
int64_t res = 0;
for (++idx; idx > 0; idx -= idx & -idx) {
res += fen[idx];
}
return res;
};
int64_t cnt = 0;
vec<vii> bl(n + 4);
update(r[0], 1);
for (int i = 1; i < n + 1; ++i) {
cnt += sum(n + 2) - sum(i - 1);
update(r[i], 1);
if (l[i] > 0) bl[l[i] - 1].emplace_back(i - 1);
}
fill(all(fen), 0);
for (int i = 0; i < n + 1; ++i) {
update(r[i], 1);
for (auto &j : bl[i]) {
cnt -= sum(n + 2) - sum(j);
}
}
for (int i = 0; i < n + 1; ++i) {
if (l[i] == 0 && r[i] == n) --cnt;
}
--cnt;
cout << cnt;
return 0;
}