P2945 [USACO09MAR]Sand Castle S

题目描述

Farmer John has built a sand castle! Like all good castles, the walls have crennelations, that nifty pattern of embrasures (gaps) and merlons (filled spaces); see the diagram below. The N (1 <= N <= 25,000) merlons of his castle wall are conveniently numbered 1..N; merlon i has height M_i (1 <= M_i <= 100,000); his merlons often have varying heights, unlike so many.

He wishes to modify the castle design in the following fashion: he has a list of numbers B_1 through B_N (1 <= B_i <= 100,000), and wants to change the merlon heights to those heights B_1, ..., B_N in some order (not necessarily the order given or any other order derived from the data).

To do this, he has hired some bovine craftsmen to raise and lower the merlons' heights. Craftsmen, of course, cost a lot of money. In particular, they charge FJ a total X (1 <= X <= 100) money per unit height added and Y (1 <= Y <= 100) money per unit height

reduced.

FJ would like to know the cheapest possible cost of modifying his sand castle if he picks the best permutation of heights. The answer is guaranteed to fit within a 32-bit signed integer.

Note: about 40% of the test data will have N <= 9, and about 60% will have N <= 18.

约翰用沙子建了一座城堡.正如所有城堡的城墙,这城墙也有许多枪眼,两个相邻枪眼中间那部分叫作“城齿”. 城墙上一共有N(1≤N≤25000)个城齿,每一个都有一个高度Mi.(1≤Mi≤100000).现在约翰想把城齿的高度调成某种顺序下的Bi,B2,…,BN(1≤Bi≤100000). -个城齿每提高一个单位的高度,约翰需要X(1≤X≤100)元;每降低一个单位的高度,约翰需要Y(1≤y≤100)元. 问约翰最少可用多少钱达到目的.数据保证答案不超过2^31-1.

输入格式

* Line 1: Three space-separated integers: N, X, and Y

* Lines 2..N+1: Line i+1 contains the two space-separated integers: M_i and B_i

输出格式

* Line 1: A single integer, the minimum cost needed to rebuild the castle

输入输出样例

输入 #1复制

3 6 5 
3 1 
1 2 
1 2 

输出 #1复制

11 

说明/提示

FJ's castle starts with heights of 3, 1, and 1. He would like to change them so that their heights are 1, 2, and 2, in some order. It costs 6 to add a unit of height and 5 to remove a unit of height.

FJ reduces the first merlon's height by 1, for a cost of 5 (yielding merlons of heights 2, 1, and 1). He then adds one unit of height to the second merlon for a cost of 6 (yielding merlons of heights 2, 2, and 1).

【算法分析】这个题看到的时候就猜应该是排序以后按照从小到大一个个更改,接下来我们来证明看为什么是这样的。

P2945 [USACO09MAR]Sand Castle S_第1张图片

假定红色是我们原来的,黑色是修改后的,红色从任选两个点a1,a2,黑色中选择点b1,b2,那么按照我们的思路消费为(a1-b1)*y+(a2-b2)*y,否则的话为(a1-b2)*y+(a2-b1)*y,这个时候我们将两个等式相减以后得0,所以如果没有相交,它们消费是固定得。

P2945 [USACO09MAR]Sand Castle S_第2张图片

接下来我们假定a1在左边,a2在右边,b1在左边,b2在右边,按照我们的思路消费为(a2-b2)*y+(b1-a1)*x,否则的话为(a2-b1)*y+(b2-a1)*x,我们用后面的公式减去前面的得到(b2-b1)*y+(b2-b1)*x=(b2-b1)*(x+y).所以当我们按照从小到大排序以后,依次计算需要的消费就可以了。 

【代码实现】

#include
using namespace std;
const int N=3e4;
int a[N],b[N];
int main()
{
	int n,x,y;
	cin>>n>>x>>y;
	for(int i=0;i>a[i]>>b[i];
	int sum=0;
	sort(a,a+n);
	sort(b,b+n);
	for(int i=0;ib[i]) sum+=(a[i]-b[i])*y;
		else sum+=(b[i]-a[i])*x;
	}
	cout<

 

你可能感兴趣的:(noip,算法)