This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define _size(x) (int)x.size()
int n;
long long ans = 0;
vector<long long> h, newH;
void solve() {
set<pair<long long, long long>> st;
for (int i = 0; i < n; i++) {
if (h[i] == newH[i]) {
if (!i) st.insert({newH[i], newH[i]});
else if (newH[i] != newH[i - 1]) st.insert({newH[i], newH[i]});
continue;
}
vector<pair<long long, long long>> g;
auto it = st.upper_bound({h[i], h[i]});
if (it != st.begin()) {
it--;
if (it->se < h[i]) it++;
}
long long x = h[i];
while (true) {
g.push_back({it->fi, it->se});
if (it->fi > x) {
if (it->fi > newH[i]) {
ans += it->fi * (newH[i] - x);
g.pop_back();
break;
}
ans += it->fi * (it->fi - x);
x = it->fi;
}
long long maxx = min(it->se, newH[i]);
ans += (maxx + x + 1) * (maxx - x) / 2;
x = maxx;
if (x == newH[i]) break;
it++;
}
for (auto seg: g) st.erase({seg.fi, seg.se});
if (_size(g)) st.insert({min(g[0].fi, h[i]), max(g.back().se, newH[i])});
else st.insert({h[i], newH[i]});
}
}
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n;
h.resize(n);
long long maxValue = 0;
for (int i = 0; i < n; i++) {
cin >> h[i];
maxValue = max(maxValue, h[i]);
}
newH.resize(n);
for (int i = 0; i < n; i++) {
if (h[i] == maxValue) break;
newH[i] = max(i ? newH[i - 1] : 0, h[i]);
}
for (int i = n - 1; i >= 0; i--) {
if (h[i] == maxValue) break;
newH[i] = max(i < n - 1 ? newH[i + 1] : 0, h[i]);
}
for (int i = 0; i < n; i++) if (newH[i] == 0) newH[i] = maxValue;
// for (int i = 0; i < n; i++) cout << "#" << i << ": " << h[i] << " and " << newH[i] << '\n';
solve();
reverse(h.begin(), h.end());
reverse(newH.begin(), newH.end());
solve();
for (int i = 0; i < n; i++) ans += (newH[i] - 1 + h[i]) * (newH[i] - h[i]) / 2;
cout << ans << '\n';
return 0;
}
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |