# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
526337 | keta_tsimakuridze | Mountain Trek Route (IZhO12_route) | C++14 | 94 ms | 9908 KiB |
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>
#define int long long
#define f first
#define s second
#define pii pair<int,int>
using namespace std;
const int N = 2e5 + 5, mod = 1e9 + 7; // !
int t, n, k, p[N], a[N], b[N], l[N], r[N];
int find(int u) {
return (p[u] == u ? u : p[u] = find(p[u]));
}
void merge(int u, int v) {
u = find(u); v = find(v);
if(u == v) return;
p[v] = u;
l[u] = min(l[u], l[v]);
r[u] = max(r[u], r[v]);
}
main(){
cin >> n >> k;
pii mx; mx = {0, 0};
for(int i = 1; i <= n; i++) cin >> b[i], p[i] = i, l[i] = r[i] = i, mx = max(mx, {b[i], i});
int c = 0;
for(int i = mx.s; i <= n; i++) a[++c] = b[i];
for(int i = 1; i < mx.s + 1; i++) a[++c] = b[i];
set<pii> s;
for(int i = 1; i <= n; i++) {
int j = i - 1;
while(j < n && a[j + 1] == a[i]) j++, merge(i, j);
find(i);
if(a[l[p[i]] - 1] > a[i] && a[r[p[i]] + 1] > a[i]) s.insert({r[p[i]] - l[p[i]] + 1, i});
i = j;
}
int ans = 0;
while(k && s.size()) {
pii x = *s.begin();
s.erase(x);
int i = x.s, len = x.f; find(i);
i = p[i];
int need = min(a[l[p[i]] - 1], a[r[p[i]] + 1]) - a[p[i]];
if(need * len >= k) {
ans += k / len * 2;
k = 0;
break;
}
ans += need * 2;
k -= need * len;
a[p[i]] = min(a[l[p[i]] - 1], a[r[p[i]] + 1]);
if(a[p[i]] == a[l[p[i]] - 1]) {
merge(p[i], l[p[i]] - 1);
}
if(a[p[i]] == a[r[p[i]] + 1]) {
merge(p[i], r[p[i]] + 1);
}
if(a[l[p[i]] - 1] > a[p[i]] && a[r[p[i]] + 1] > a[p[i]]) s.insert({r[p[i]] - l[p[i]] + 1, i});
}
cout << ans;
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |