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
#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)/~

你可能感兴趣的:(Restorer Distance CodeForces - 1355E(三分+贪心))