GYM 101149 B.No Time for Dragons【二分+贪心】

142 篇文章 0 订阅
75 篇文章 0 订阅

B. No Time for Dragons
time limit per test
2.0 s
memory limit per test
256 MB
input
standard input
output
standard output

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.

Input

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

Output a single integer — the minimal number of soldiers that is sufficient to kill all the dragons.

Examples
input
2
7 4
5 1
output
8
input
3
4 1
6 4
5 3
output
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);
    }
}









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值