题意:每层楼都有一个重量W一个强度S,每一层楼的潜在伤害值等于 (Σwj)-si,其中 (Σwj)表示第i楼以上的所有楼层的重量之和。
求如何摆放使得最大伤害值最小。
题解:首先要确定两层楼之间要怎样调整才能使结果最小->考虑任意相邻的两层楼->任意不相邻的两层楼->得到贪心策略。
交换顺序之前:PDV1 = Wtop - Si; PDV2 =Wtop + Wi - Sj (i上,j下)
交换顺序之后:PDV1= Wtop - Sj; PDV2 = Wtop + Wj - Si (j上,i下)
如果交换顺序之后结果更小,则满足 max(Wtop-Si, Wtop+Wi-Sj) > max(Wtop-Sj, Wtop+Wj-Si)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct NODE { int w, s; } a[200000];
int cmp(const void *p1, const void *p2)
{
NODE *p3 = (NODE*)p1;
NODE *p4 = (NODE*)p2;
int w1 = p3->w, s1 = p3->s;
int w2 = p4->w, s2 = p4->s;
return max(-s1, w1 - s2) - max(-s2, w2 - s1);
//return (w1+s1) - (w2+s2);
}
int main()
{
int N;
while(scanf("%d",&N) != EOF)
{
for(int i = 0; i < N; i++)
scanf("%d%d", &a[i].w, &a[i].s);
qsort(a, N, sizeof(NODE), cmp);
__int64 topSum = 0, res = 0;
for(int i = 1; i < N; i++)
{
topSum += a[i-1].w;
res = max(res, topSum - a[i].s);
}
printf("%I64d\n",res);
}
return 0;
}