// Har Har Mahadev
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define int long long
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rrep(i,a,b) for(int i=a;i>=b;i--)
#define repin rep(i,0,n)
#define precise(i) cout<<fixed<<setprecision(i)
#define vi vector<int>
#define si set<int>
#define mii map<int,int>
#define take(a,n) for(int j=0;j<n;j++) cin>>a[j];
#define give(a,n) for(int j=0;j<n;j++) cout<<a[j]<<' ';
#define vpii vector<pair<int,int>>
#define db double
#define be(x) x.begin(),x.end()
#define pii pair<int,int>
#define pb push_back
#define pob pop_back
#define ff first
#define ss second
#define lb lower_bound
#define ub upper_bound
#define bpc(x) __builtin_popcountll(x)
#define btz(x) __builtin_ctz(x)
using namespace std;
using namespace __gnu_pbds;
typedef tree<int, null_type, less<int>, rb_tree_tag,tree_order_statistics_node_update> ordered_set;
typedef tree<pair<int, int>, null_type,less<pair<int, int> >, rb_tree_tag,tree_order_statistics_node_update> ordered_multiset;
const long long INF=1e18;
const long long M=1e9+7;
const long long MM=998244353;
int power( int N, int M){
int power = N, sum = 1;
if(N == 0) sum = 0;
while(M > 0){if((M & 1) == 1){sum *= power;}
power = power * power;M = M >> 1;}
return sum;
}
void solve()
{
int n;
cin >> n;
vi a(n),b(n);
vi d(n);
repin{
cin >> a[i] >> b[i];
d[i] = a[i]-b[i];
if(i)d[i] += d[i-1];
}
if(n == 1){
cout << 0 << "\n";
return;
}
int ans = 0;
repin{
//since minimum element must be greater than zero
if(d[i] < 0)ans -= d[i],d[i] = 0;
}
multiset<int> ms;
// ms.insert(0);
rep(i,0,n-1){
ms.insert(d[i]);
auto it = ms.end();
it--;
ans += (*it)-d[i];
ms.insert(d[i]);
it = ms.end();
it--;
ms.erase(it);
}
//finding ans at d.back()
auto it = ms.end();
it--;
int nx = (*it);
ms.erase(it);
if(d.back() >= nx){
cout << ans << "\n";return;
}
int cnt = 1;
while(ms.size()){
auto it = ms.end();
it--;
auto res = (*it);
ms.erase(it);
if(d.back() >= res){
ans += (nx-d.back())*cnt;
nx = 0;
break;
}
ans += (nx-res)*cnt;
nx = res;
cnt++;
}
if(nx-d.back()>0)ans += (nx-d.back())*cnt;
cout << ans << "\n";
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
#ifdef NCR
init();
#endif
#ifdef SIEVE
sieve();
#endif
solve();
return 0;
}
# | 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... |