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);
}
int ans = 0;
for (int i = 0; i < n; i++) {
if (a[i] >= b[i]) continue;
auto r = st.upper_bound(i);
auto l = r;
if (l != st.begin()) l--;
vector<int> to_erase;
while (a[i] < b[i]) {
int x = *l;
int y = (r == st.end() ? -1 : *r);
int d1 = abs(x - i);
int d2 = abs(y - i);
if (x < i && ((r == st.end()) || (a[y] <= b[y]) || (a[x] > b[x] && d1 <= d2))) {
int z = a[x]-b[x];
int z2 = b[i]-a[i];
if (z > z2) {
a[x] -= z2;
ans += z2*d1;
a[i] = b[i];
}
else {
ans += z*d1;
a[i] += z;
a[x] = b[x];
to_erase.push_back(x);
if (l != st.begin()) l--;
}
}
else {
int z = a[y]-b[y];
int z2 = b[i]-a[i];
if (z > z2) {
a[y] -= z2;
ans += z2*d2;
a[i] = b[i];
}
else {
ans += z*d2;
a[i] += z;
a[y] = b[y];
to_erase.push_back(y);
if (r != st.end()) r++;
}
}
}
for (int& j : to_erase) st.erase(j);
}
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... |