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;
using ll = long long;
void solve() {
int n;
cin >> n;
vector<pair<int, int>> a(n);
set<int> pos;
for (int i = 0; i < n; i++) {
cin >> a[i].first >> a[i].second;
if (a[i].first > a[i].second) {
pos.insert(i);
}
}
int j = 0;
ll ans = 0;
for (int i = 0; i < n; i++) {
if (a[i].first >= a[i].second) {
continue;
}
while (a[i].first < a[i].second) {
while (j < i and a[j].first <= a[j].second) {
j++;
}
if (j != i) {
int x = min(a[i].second - a[i].first, a[j].first - a[j].second);
a[i].first += x;
a[j].first -= x;
ans += 1ll * x * abs(j - i);
} else {
break;
}
}
while (a[i].first < a[i].second) {
int k = *pos.lower_bound(i);
int x = min(a[i].second - a[i].first, a[k].first - a[k].second);
a[i].first += x;
a[k].first -= x;
ans += 1ll * x * abs(k - i);
if (a[k].first == a[k].second) {
pos.erase(k);
}
}
}
cout << ans;
}
int main() {
ios_base::sync_with_stdio(false);
cout.tie(nullptr);
cin.tie(nullptr);
int queries = 1;
#ifdef test_cases
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
cin >> queries;
#else
// cin >> queries;
#endif
for (int test_case = 1; test_case <= queries; test_case++) {
solve();
cout << '\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... |