B. No Time for Dragons(贪心)

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 ai soldiers, 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 的军队,问最小需要派出的军队数是?


//题解:想到的都说很简单,但我很久都没想通,我的理解是,逆序思考,假如杀完所有龙后,剩下 x 个人,使 x 尽量小就是使ans尽量小。
对于每只龙,可以这么考虑,设 ci = ai - bi; 就变为了:
需要 x >= ci 人 ,x 才能 +bi ,所以,为了让 x 尽量小,对 ci 进行排序,就让 x 在尽量小的情况下加更多 bi,就能使 ans 最小了
 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 #include <algorithm>
 5 using namespace std;
 6 #define LL long long
 7 #define MX 200005
 8 struct Dr
 9 {
10     LL a,b;
11     bool operator < (const Dr &x)const
12     {
13         return a-b<x.a-x.b;
14     }
15 }dr[MX];
16 
17 int main()
18 {
19     int n;
20     cin>>n;
21     for (int i=0;i<n;i++)
22         scanf("%lld%lld",&dr[i].a,&dr[i].b);
23     sort(dr,dr+n);
24     LL ans =0;
25     for (int i=0;i<n;i++)
26     {
27         if (ans<dr[i].a-dr[i].b)
28             ans=dr[i].a;
29         else
30             ans += dr[i].b;
31     }
32     cout<<ans<<endl;
33     return 0;
34 }
View Code
 
原文地址:https://www.cnblogs.com/haoabcd2010/p/7252267.html