POJ-3045-Co-Acrobats
题目描述:
Farmer John’s N (1 <= N <= 50,000) cows (numbered 1..N) are planning to run away and join the circus. Their hoofed feet prevent them from tightrope walking and swinging from the trapeze (and their last attempt at firing a cow out of a cannon met with a dismal failure). Thus, they have decided to practice performing acrobatic stunts.
The cows aren’t terribly creative and have only come up with one acrobatic stunt: standing on top of each other to form a vertical stack of some height. The cows are trying to figure out the order in which they should arrange themselves ithin this stack.
Each of the N cows has an associated weight (1 <= W_i <= 10,000) and strength (1 <= S_i <= 1,000,000,000). The risk of a cow collapsing is equal to the combined weight of all cows on top of her (not including her own weight, of course) minus her strength (so that a stronger cow has a lower risk). Your task is to determine an ordering of the cows that minimizes the greatest risk of collapse for any of the cows.
输入:
Line 1: A single line with the integer N.
Lines 2..N+1: Line i+1 describes cow i with two space-separated integers, W_i and S_i.
输出:
- Line 1: A single integer, giving the largest risk of all the cows in any optimal ordering that minimizes the risk.
输入示例:
1 | 3 |
输出示例:
1 | 2 |
提示:
OUTPUT DETAILS:
Put the cow with weight 10 on the bottom. She will carry the other two cows, so the risk of her collapsing is 2+3-3=2. The other cows have lower risk of collapsing.
题目大意:
有N头牛,每个牛有一定的重量w和力量s,将这N头牛叠罗汉,每头牛有一个风险值,为它背上所有牛的重量减去他的力量。求最大风险值,并要求最大风险值尽可能小。
思路:
该题就是要找到一个最优排列,让最大风险值尽可能小,显然的,重的牛应该尽可能的安排在下方,同样,力气大的牛也应该尽可能安排在下方。
结论:
将力量与重量之和从小到大排列。
证明一:
对于每头牛而言,将它与它上面的牛作为一个整体,总的重量为sum_w,则该牛的风险值为:
1 | (sum_w-w-s)=(sum_w-(w+s)) |
我们要想取到最优解,就要sum_w-(w+s)的值最小,w+s就应该最大,所以w+s越大越应该在下面。
证明二:
假设当前的排列是最优的。任意位置上有第一头牛和第二头牛,第一头牛在第二头牛的上面,第一头牛上面的重量总和为sum,第一头牛和第二头牛的重量和力量分别为w1、s1、w2、s2,可以知道两头牛的危险值分别为 a = sum-s1, b = sum+w1-s2。
现在调换两头牛的位置,则a1 = sum+w1-s1, b1 = sum-s2。
因为之前是最优解,可得:
1 | sum+w2-s1 >= sum+w1-s2 |
移项可得:
1 | w2+s2 >= w1+s1 |
所以重量与力量和越大越在下方。
Solution:
1 | /* |