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 int long long
const int N = 1e6+6;
int n, a[N], b[N];
set<int> st;
signed main() {
ios::sync_with_stdio(false); cin.tie(nullptr);
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i] >> b[i];
if (a[i] > b[i]) st.insert(i);
}
st.insert(-1);
st.insert(n);
int ans = 0;
for (int i = 0; i < n; i++) {
if (a[i] >= b[i]) continue;
while (a[i] < b[i]) {
auto l = prev(st.lower_bound(i));
auto r = st.lower_bound(i);
int x = *l;
int y = *r;
int d1 = abs(x - i);
int d2 = abs(y - i);
if (y == n || (x != -1 && d1 <= d2)) {
int z = a[x]-b[x];
int z2 = b[i]-a[i];
int z3 = min(z, z2);
a[i] += z3;
a[x] -= z3;
ans += z3*d1;
if (a[x] == b[x]) st.erase(x);
}
else {
int z = a[y]-b[y];
int z2 = b[i]-a[i];
int z3 = min(z, z2);
a[i] += z3;
a[y] -= z3;
ans += z3*d2;
if (a[y] == b[y]) st.erase(y);
}
}
}
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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |