This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
//subtask2
#include <iostream>
#include <vector>
#include <set>
using namespace std;
using ll = long long;
struct stree {
#define lc v*2
#define rc v*2+1
vector <int> tree;
stree (int s) {
tree.resize(s * 4);
}
void pushup(int v) {
tree[v] = max(tree[lc], tree[rc]);
}
void update(int v, int tl, int tr, int p, int val) {
if (tl > p || tr < p)
return;
if (tl == tr) {
tree[v] = val;
return;
}
int tm = (tl + tr) / 2;
update(lc, tl, tm, p, val);
update(rc, tm+1, tr, p, val);
pushup(v);
}
int query(int v, int tl, int tr, int l, int r) {
if (tl > r || tr < l)
return 0;
if (tl >= l && tr <= r)
return tree[v];
int tm = (tl + tr) / 2;
int a = query(lc, tl, tm, l, r);
int b = query(rc, tm+1, tr, l, r);
return max(a, b);
}
};
int main() {
int n;
cin >> n;
multiset <pair <int, int>> s;
multiset <pair <int, int>> rngs;
rngs.insert({1, n});
stree tree(n+1);
for (int i = 1; i <= n; i++) {
int t;
cin >> t;
tree.update(1, 1, n, i, t);
s.insert({t, i});
}
vector <bool> rem(n+1);
ll ans = 0;
while (!s.empty()) {
int mx = s.rbegin()->first;
int pos = s.rbegin()->second;
auto tp = rngs.upper_bound({pos, pos});
tp--;
int l = tp->first, r = tp->second;
rngs.erase(tp);
s.erase(--s.end());
int added = 0;
if (pos+1 <= n && !rem[pos+1]) {
ans += tree.query(1, 1, n, pos+1, r);
added++;
}
if (pos-1 >= 1 && !rem[pos-1]) {
ans += tree.query(1, 1, n, l, pos-1);
added++;
}
rem[pos] = true;
tree.update(1, 1, n, pos, 0);
ans += mx * added;
if (l == r)
continue;
if (pos == l)
rngs.insert({l+1, r});
else if (pos == r)
rngs.insert({l, r-1});
else {
rngs.insert({l, pos-1});
rngs.insert({pos+1, r});
}
}
cout << ans << '\n';
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |