链接: https://codeforces.com/problemset/problem/1539/D.
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
typedef long long ll;
typedef unsigned long long ull;
#define speed(x) ios::sync_with_stdio(false), cin.tie(x), cout.tie(x)
#define bug(x) cout << #x << " == " << x << '\n'
const ll MAX_N = 3e5 + 5;
struct node
{
ll lim;
ll need;
bool operator < (node b)
{
return lim<b.lim;
}
}a[MAX_N];
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%lld %lld",&a[i].need,&a[i].lim);
}
sort(a+1,a+1+n);
int l=1,r=n;
ll cnt=0;///购买物品数
ll sum=0;
while(l<=r)
{
if(a[l].lim <= cnt)
{
sum+=a[l].need;///因为在满足限制的时候买的所以肯定就是半价
cnt+=a[l].need;
l++;
}
else
{
ll now=min(a[l].lim-cnt,a[r].need);
///直接购买第r件商品,因为这个商品最难打折,一种可能是直接购买到需求数,另一种是购买到刚刚好买l件商品可以打折的数量
sum += (2*now);
cnt += now;
a[r].need-=now;
if(a[r].need==0)r--;///买完了
}
}
printf("%lld\n",sum);
}