One fairy king hated dragons to death. Not only that these monsters burn whole villages to ashes, kidnap princesses and guard treasures that they don't need at all, but they are also mentioned in statements of programming problems very often. To end their tyranny, he decided to recruit an army and destroy these damned creatures once and forever.
The king found out that there are n dragons in total, and to defeat the i-th of them he needs an army of aisoldiers, bi of which will be killed during the battle. Now he wants to know the minimal number of soldiers he needs to recruit in order to kill all the dragons. The king doesn't care about the order of battles: the only thing that matters is that none of the dragons will be left alive.
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of dragons.
Each of the next n lines contains two space-separated integers: ai and bi (1 ≤ bi ≤ ai ≤ 109) — the number of soldiers needed to defeat the i-th dragon, and the number of soldiers that will be killed in the battle against him.
Output a single integer — the minimal number of soldiers that is sufficient to kill all the dragons.
2 7 4 5 1
8
3 4 1 6 4 5 3
10
现在有n个敌人需要打败,已知打败第i个敌人需要ai个兵,并且会死掉bi个兵。我们不在乎打败敌人的顺序,我们只希望派出尽可能少的兵去打败所有的敌人。
问最少需要多少人。
思路:
我们知道,会死掉的人数是固定的,我们肯定希望第一场战役打完之后,剩余的人尽可能的多,这样剩余的人可以留到下一战役。所以我们对a【i】-b【i】排序,然后二分答案模拟一下打败敌人的过程判定一下当前答案是否合法即可。
最少的兵显然有单调性,二分过程维护解就行了。
Ac代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long int
struct node
{
int ned,del,cha;
}a[350000];
int n;
int cmp(node a,node b)
{
return a.cha>b.cha;
}
int Slove(ll mid)
{
for(int i=1;i<=n;i++)
{
if(mid>=a[i].ned)mid-=a[i].del;
else return 0;
}
return 1;
}
int main()
{
while(~scanf("%d",&n))
{
for(int i=1;i<=n;i++)scanf("%d%d",&a[i].ned,&a[i].del),a[i].cha=a[i].ned-a[i].del;
sort(a+1,a+1+n,cmp);
ll ans;
ll l=1;
ll r=1e18;
while(r-l>=0)
{
ll mid=(l+r)/2;
if(Slove(mid)==1)
{
r=mid-1;
ans=mid;
}
else l=mid+1;
}
printf("%lld\n",ans);
}
}