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).

【算法分析】這個題看到的時候就猜應該是排序以後按照從小到大一個個更改,接下來我們來證明看爲什麼是這樣的。

假定紅色是我們原來的,黑色是修改後的,紅色從任選兩個點a1,a2,黑色中選擇點b1,b2,那麼按照我們的思路消費爲(a1-b1)*y+(a2-b2)*y,否則的話爲(a1-b2)*y+(a2-b1)*y,這個時候我們將兩個等式相減以後得0,所以如果沒有相交,它們消費是固定得。

接下來我們假定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<bits/stdc++.h>
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<n;i++)
		cin>>a[i]>>b[i];
	int sum=0;
	sort(a,a+n);
	sort(b,b+n);
	for(int i=0;i<n;i++)
	{
		if(a[i]>b[i]) sum+=(a[i]-b[i])*y;
		else sum+=(b[i]-a[i])*x;
	}
	cout<<sum;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章