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;
int n;
int h[1000005];
set<int> active;
class state{
public:
int i, j; // join(i,j); (i < j)
long long diff;
state(int x, int y, long long d) : i(x), j(y), diff(d) {}
friend bool operator<(const state& x, const state& y){
return x.diff > y.diff;
}
};
long long computeDiff(int i, int j){
assert(i < j);
return -1ll*(n-j+1)*h[j] -1ll*(n-i+1)*h[i] + 1ll*(n-i+1)*h[j];
}
bool verifyDiff(state cur){
int i = cur.i;
int j = cur.j;
long long diff = cur.diff;
return active.count(i) && active.count(j) && computeDiff(i,j) == diff;
}
int main(){
scanf("%d",&n);
long long ans = 0ll;
int mx = 0;
vector<int> pivots;
for(int i = 1; i <= n; i++){
scanf("%d",h+i);
if(h[i] > mx){
mx = h[i];
pivots.push_back(i);
ans += 1ll * mx * (n-i+1);
}
}
priority_queue<state> pq;
for(int i = 0; i < pivots.size()-1; i++){
int idx = pivots[i];
int nidx = pivots[i+1];
long long diff = computeDiff(idx, nidx);
pq.emplace(idx, nidx, diff);
active.insert(idx);
}
active.insert(pivots.back());
while(!pq.empty() && pq.top().diff < 0ll){
state cur = pq.top();
pq.pop();
if(!verifyDiff(cur)) continue;
ans += cur.diff;
h[cur.i] = h[cur.j];
active.erase(cur.j);
auto it = active.upper_bound(cur.j);
if(it != active.end()){
int nxtj = *it;
long long diff = computeDiff(cur.i, nxtj);
pq.emplace(cur.i, nxtj, diff);
}
it = active.lower_bound(cur.i);
if(it != active.begin()){
--it;
int prej = *it;
long long diff = computeDiff(prej, cur.i);
pq.emplace(prej, cur.i, diff);
}
}
printf("%lld\n", ans);
return 0;
}
Compilation message (stderr)
Discharging.cpp: In function 'int main()':
Discharging.cpp:39:19: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
39 | for(int i = 0; i < pivots.size()-1; i++){
| ~~^~~~~~~~~~~~~~~~~
Discharging.cpp:26:7: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
26 | scanf("%d",&n);
| ~~~~~^~~~~~~~~
Discharging.cpp:31:8: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
31 | scanf("%d",h+i);
| ~~~~~^~~~~~~~~~
# | 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... |