CodeForces_1355E Restorer Distance(三分)

Restorer Distance

time limit per test:1 seconds
memory limit per test:256 megabytes

Problem Description

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 ≤ 1 0 5 1≤N≤10^5 1N105, 0 ≤ A , R , M ≤ 1 0 4 0≤A,R,M≤10^4 0A,R,M104) — the number of pillars and the costs of operations.

The second line contains N integers h i h_i hi ( 0 ≤ h i ≤ 1 0 9 0≤h_i≤10^9 0hi109) — initial heights of pillars.

Output

Print one integer — the minimal cost of restoration.

Sample Input

3 1 100 100
1 3 8

Sample Output

12

题意

有n个柱子,每个柱子初始高度为ai.可进行一下三种操作:

  • 将一个柱子的高度加一,代价为a
  • 将一个柱子的高度减一,代价为r
  • 将一个柱子的高度加一并把另一个柱子的高度减一,代价为m

求令所有柱子高度相同的最少代价。

题解

设最终高度为h,则可以遍历求出需要进行增加操作up次,减少操作dn次。若a+r>m,则可以将min(up,dn)次的增加操作和min(up,dn)次的减少操作变为min(up,dn)次转移操作。计算代价和,即可求出所有柱子高度变为h的最少花费。
最终高度h和最少花费的关系图形类似 y = x 2 y=x^2 y=x2的图形,三分求最优解即可。

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define dbg(x) cout<<#x<<" = "<
#define INF 0x3f3f3f3f
#define eps 1e-6
 
using namespace std;
typedef long long LL;   
typedef pair<int, int> P;
const int maxn = 100100;
const int mod = 1000000007;
int a, r, m, b[maxn];
LL isok(int n, int mid);

int main()
{
    int n, i, j, k;
    LL ans = 1e18;
    scanf("%d %d %d %d", &n, &a, &r, &m);
    for(i=0;i<n;i++)
        scanf("%d", &b[i]);
    int l = 0, r = 1e9;
    while(l+5<r)
    {
        int mid = (r-l+1)/3;
        int mid1 = l+mid, mid2 = l+mid+mid;
        LL sum1 = isok(n, mid1), sum2 = isok(n, mid2);
        if(sum1 > sum2)l = mid1;
        else r = mid2;
    }
    for(i=l;i<=r;i++)ans = min(ans, isok(n, i));
    printf("%I64d\n", ans);
    return 0;
}

LL isok(int n, int mid)
{
    LL ans = 0, up = 0, dn = 0;
    for(int i=0;i<n;i++)
        if(b[i] < mid)up += mid-b[i];
        else dn += b[i]-mid;
    ans = a*up+r*dn;
    LL x = min(up, dn);
    if(a+r > m)ans += m*x-x*a-x*r;
    return ans;
}

你可能感兴趣的:(二分,三分)