fork(2) download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4. #define FAST1 ios_base::sync_with_stdio(false);
  5. #define FAST2 cin.tie(NULL);
  6.  
  7. bool sort_on_second(pair<ll,ll> left, pair<ll,ll> right){
  8. return left.second<right.second;
  9. }
  10. void solve(){
  11. ll n;
  12. cin>>n;
  13. vector<pair<ll,ll>> arr(n);
  14. ll ans=0;
  15. for(ll i=0;i<n;i++)
  16. {
  17. cin>>arr[i].first>>arr[i].second;
  18. ans+=2*arr[i].first;
  19. }
  20. sort(arr.begin(),arr.end(),sort_on_second);
  21. reverse(arr.begin(),arr.end());
  22. ll i=0,j=n-1;
  23. ll cur =0;
  24. while(i<=j){
  25. ll tar=arr[j].second;
  26. if(i==j){
  27. ll can_take=arr[i].first;
  28. ll to_take=max(0ll,arr[i].second-cur);
  29. can_take=max(0ll,can_take-to_take);
  30. ans-=can_take;
  31. break;
  32. }
  33. else if(cur>=tar){
  34. cur+=arr[j].first;
  35. ans-=arr[j].first;
  36. j--;
  37. }
  38. else if(cur+arr[i].first<=arr[j].second){
  39. cur+=arr[i].first;
  40. arr[i].first=0;
  41. i++;
  42. }
  43. else{
  44. ll to_take=arr[j].second-cur;
  45. cur+=to_take;
  46. cur+=arr[j].first;
  47. arr[i].first-=to_take;;
  48. ans-=arr[j].first;
  49. j--;
  50. }
  51. }
  52. cout<<ans<<endl;
  53.  
  54. }
  55.  
  56. int main(){
  57. FAST1;
  58. FAST2;
  59. ll t=1;
  60. while(t--){
  61. solve();
  62. }
  63. }
  64.  
Success #stdin #stdout 0s 5676KB
stdin
3
3 4
1 3
1 5
stdout
8