Restorer Distance CodeForces - 1355E(三分+贪心)

You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to hi, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.

You are allowed the following operations:

put a brick on top of one pillar, the cost of this operation is A;
remove a brick from the top of one non-empty pillar, the cost of this operation is R;
move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.

What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?

Input
The first line of input contains four integers N, A, R, M (1≤N≤105, 0≤A,R,M≤104) — the number of pillars and the costs of operations.

The second line contains N integers hi (0≤hi≤109) — initial heights of pillars.

Output
Print one integer — the minimal cost of restoration.

Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3
思路:我们可以通过分析样例发现,需要的价值是一个开口向上的抛物线。这是三分的标志。我们三分去取最小值。那么贪心的规则是什么呢?
如果A+R<=M的话,那么每一个元素该加的加,该减的减。
如果A+R>M的话,那么我们就应该尽量多的互补一下,实在不行了在增加或者减少。
代码如下:

#include<bits/stdc++.h>
#define ll long long
using namespace std;

const int maxx=1e5+100;
int a[maxx];
int n,b,r,m;

inline ll judge(int x)
{
	ll ans=0;
	if(b+r<=m)
	{
		for(int i=1;i<=n;i++)
		{
			if(a[i]<x) ans+=(ll)(x-a[i])*(ll)b;
			else if(a[i]>x) ans+=(ll)(a[i]-x)*(ll)r;
		}
		return ans;
	}
	ll pre=0;
	for(int i=n;i>=1;i--)
	{
		if(a[i]>x) ans+=(ll)(a[i]-x)*(ll)m,pre+=(ll)(a[i]-x);
		else if(a[i]<x) 
		{
			if(pre>=x-a[i]) pre-=(ll)(x-a[i]);
			else
			{
				ans+=(ll)(x-a[i]-pre)*(ll)b;
				pre=0;
			}
		}
	}
	if(pre) ans-=(ll)(m-r)*(ll)pre;
	return ans;
}
int main()
{
	scanf("%d%d%d%d",&n,&b,&r,&m);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	sort(a+1,a+1+n);
	int l=a[1],r=a[n];
	int lmid,rmid,ans;
	while(l<=r)
	{
		lmid=l+(r-l)/3;
		rmid=r-(r-l)/3;
		if(judge(lmid)<judge(rmid)) r=rmid-1;
		else l=lmid+1;
	}
	printf("%lld\n",min(judge(r),judge(l)));
	return 0;
}

努力加油a啊,(o)/~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

starlet_kiss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值