HDU 4296 buildings

探讨了通过贪心算法解决楼板排列问题的方法,旨在寻找使得整栋楼的pdv值最小的楼板排列方式。
题目链接:点击打开链接
题目大意:一栋楼有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).
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.
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;
}
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值