#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
using pii = pair<i64, i64>;
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,avx2,mmx,fma,avx,tune=native")
const int N = 500'000, inf = 1'000'000'000;
const i64 infl = 1'000'000'000'000'000'000;
const int mod1 = 1'000'000'009, mod2 = 998'244'353;
const int p1 = 31, p2 = 37;
#define ff first
#define ss second
#define pb push_back
#define ins insert
#define sz(x) (int)(x).size()
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define NO cout << "NO\n"
#define YES cout << "YES\n"
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int __tc = 1;
i64 n, ans = 0;
pii a[N+5];
i64 st[2][21][N+5];
void solve() {
sort(a + 1, a + n + 1);
for (int i = 1; i <= n; i++) {
st[0][0][i] = a[i].ff;
st[1][0][i] = a[i].ff;
}
for (int l = 1; l <= 19; l++) {
for (int i = 1; i + (1 << l) - 1 <= n; i++) {
st[0][l][i] = min(st[0][l-1][i], st[0][l-1][i + (1 << (l - 1))]);
st[1][l][i] = max(st[1][l-1][i], st[1][l-1][i + (1 << (l - 1))]);
}
}
i64 cs = 0, gs = 0;
for (int l = 1, r = 1; r <= n; r++) {
cs += a[r].ss;
int t = __lg(r - l + 1);
i64 mx = max(st[1][t][l], st[1][t][r - (1 << t) + 1]), mn = min(st[0][t][l], st[0][t][r - (1 << t) + 1]);
gs = max(gs, cs - mx + mn);
while (cs - mx + mn < 0) {
cs -= a[l].ss;
l++;
if (l > r) break;
t = __lg(r - l + 1);
mx = max(st[1][t][l], st[1][t][r - (1 << t) + 1]), mn = min(st[0][t][l], st[0][t][r - (1 << t) + 1]);
}
}
cout << gs;
}
int main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr);
// cin >> __tc;
for (int _tc = 1; _tc <= __tc; _tc++) {
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i].ff >> a[i].ss;
solve();
}
}
// sliding window: it should pass IMO
# | 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... |