[洛谷]P2945 [USACO09MAR]沙堡Sand Castle (#贪心 -1.8)

题目描述

约翰用沙子建了一座城堡.正如所有城堡的城墙,这城墙也有许多枪眼,两个相邻枪眼中间那部分叫作“城齿”. 城墙上一共有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 

思路

简单的一道贪心。

先把前后城齿排一次序,然后比较相对应城齿大小,就搞定了。

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int a[100001],b[100001];
long long int s;
int main()
{
	ios::sync_with_stdio(false);
	int m,n,x,y;
	register int i;
	cin>>n>>x>>y;
	for(i=1;i<=n;i++)
		cin>>a[i]>>b[i];
	sort(a+1,a+n+1);
	sort(b+1,b+n+1);
	for(i=1;i<=n;i++)
	{
		if(a[i]<b[i])
		{
			s=s+x*(b[i]-a[i]);
		}
		else if(a[i]>b[i])
		{
			s=s+y*(a[i]-b[i]);
		}
	}
	cout<<s<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Apro1066/article/details/81266679