题目大意:
一组整数
A
,数组大小为
现在给你一个“不完美”数组
A
,并且你可以进行下面两种操作:
1. 选择不同的两个元素
2. 选择一个元素
你可以利用1和2操作改变数组
问:最少需要花多少元,可以使数组 A 变为“完美”数组?
限制:
其中, i∈[1,N] .
问题分析
可以看到限制条件的规模很小,那么我们可以得到每种可能的“完美”数组。例如:
A=[1,2,3],k=1,l=2
,有多种完美数组:
A1=[2,2,2],A2=[3,3,3]
等等。但是仔细分析,发现几点性质:
1. 最大的“完美”数组是
Amax=[Amax,...,Amax]
。因为比它还大的完美数组,花费更多。
2. 所有完美数组都需要满足
N∗h≥s
,其中
h
是完美数组的元素值(完美数组定义),
注意:性质2成立的原因是操作1不会增加数组和,操作2只能增加数组和(+1)。
根据性质1和2,遍历所有完美数组。
HackeRank题目链接:
Beautiful Array:https://www.hackerrank.com/contests/hourrank-1/challenges
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n, k, l;
scanf("%d%d%d", &n, &k, &l);
vector<int> nums(n);
int maxV(0), minV(1001), sum(0);
for(int i = 0; i < n; ++i){
scanf("%d", &nums[i]);
sum += nums[i];
maxV = max(maxV, nums[i]);
}
int res = 1e9+7;
for(int ave = ceil((1.0*sum/n)); ave <= maxV; ++ave){
int cost(0), two(0);
for(int i = 0; i < n; ++i){
two += max(0, nums[i]-ave);
}
cost = two*k + (n*ave - sum)*l;
res = min(res, cost);
}
printf("%d\n", res);
return 0;
}