题目链接:点击打开链接
题目大意:一栋楼有n层,每层楼板有个w值和s值,这座建筑有个pdv值=最底层以上(不包括最底层)的w的总和-最底层的s值。现在要你排列每层楼板,使得这栋楼的pdv值最小,并且输出这个pdv值。
Input
There’re several test cases.
In each test case, in the first line is a single integer N (1 <= N <= 10 5) denoting the number of building’s floors. The following N lines specify the floors. Each of them contains two integers w i and s i (0 <= w i, s i <= 100000) separated by single spaces.
Please process until EOF (End Of File).
In each test case, in the first line is a single integer N (1 <= N <= 10 5) denoting the number of building’s floors. The following N lines specify the floors. Each of them contains two integers w i and s i (0 <= w i, s i <= 100000) separated by single spaces.
Please process until EOF (End Of File).
Output
For each test case, your program should output a single integer in a single line - the minimal PDV of the whole building.
If no floor would be damaged in a optimal configuration (that is, minimal PDV is non-positive) you should output 0.
If no floor would be damaged in a optimal configuration (that is, minimal PDV is non-positive) you should output 0.
Sample Input
3 10 6 2 3 5 4 2 2 2 2 2 3 10 3 2 5 3 3
Sample Output
1 0 2思路:试着证明一下其贪心依据。假设x,y是两个相邻的楼板,x在上,y在下。“W总”表示x以上的的楼板的的w值的总和。此时,pdv1 = ‘W总’+Wx - Sy。如果交换这两个楼板,那么pdv2 = ‘W总’+Wy - Sx,要使得交换后pdv值比原来的要小的充要条件是pdv2< pdv1,即‘W总’+Wx - Sy < ‘W总’+Wy - Sx,化简得Wx + Sx<Wy + Sy.所以得到的贪心依据是w与s的和最小。代码如下:
#include<iostream> #include<algorithm> using namespace std; #define LL long long const int MAX = 100000 + 100; struct node { int w; int s; }A[MAX]; int cmp( node a , node b) { return a.s + a.w < b.s + b.w ; } int main() { int i,n; while(cin >> n) { for(i = 0; i < n ; i++) cin >> A[i].w >> A[i].s; sort(A,A+n,cmp); LL sum = 0 ,pdv = 0; for(i = 0; i < n;i++) { pdv = max(pdv,sum-A[i].s); sum += A[i].w; } printf("%I64d\n",pdv); } return 0; }