いっしょ / Be Together(AtCoder-2019)

Problem Description

Evi has N integers a1,a2,..,aN. His objective is to have N equal integers by transforming some of them.

He may transform each integer at most once. Transforming an integer x into another integer y costs him (x−y)2 dollars. Even if ai=aj(i≠j), he has to pay the cost separately for transforming each of them (See Sample 2).

Find the minimum total cost to achieve his objective.

Constraints

1≦N≦100
−100≦ai≦100

Input

The input is given from Standard Input in the following format:

N
a1 a2 ... aN

Output

Print the minimum total cost to achieve Evi's objective.

Example

Sample Input 1

2
4 8

Sample Output 1

8
Transforming the both into 6s will cost (4−6)2+(8−6)2=8 dollars, which is the minimum.

Sample Input 2

3
1 1 3

Sample Output 2

34

Sample Input 3

3
Transforming the all into 2s will cost (1−2)2+(1−2)2+(3−2)2=3 dollars. Note that Evi has to pay (1−2)2 dollar separately for transforming each of the two 1s.

Sample Output 3

5
Leaving the 4 as it is and transforming the 2 and the 5 into 4s will achieve the total cost of (2−4)2+(5−4)2=5 dollars, which is the minimum.

Sample Input 4

4
-100 -100 -100 -100

Sample Output 4

0
Without transforming anything, Evi's objective is already achieved. Thus, the necessary cost is 0.

题意:给出 n 个数,现在要让这 n 个数变为相同的值,对这些数只能进行一次转换,每次将数 x 变为数 y 花费 (x-y)^2 的,求最小的花费

思路:数据范围不大,直接考虑暴力枚举即可

首先要变的数肯定在这 n 个数的最大值到最小值之间,然后两重循环进行枚举统计最小值即可

Source Program

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 200+5;
const int dx[] = {0,0,-1,1,-1,-1,1,1};
const int dy[] = {-1,1,0,0,-1,1,-1,1};
using namespace std;
int a[N];
int main(){

    int n;
    scanf("%d",&n);
    int minn=INF,maxx=-INF;
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        minn=min(minn,a[i]);
        maxx=max(maxx,a[i]);
    }

    int res=INF;
    for(int i=minn;i<=maxx;i++){
        int temp=0;
        for(int j=1;j<=n;j++)
            temp+=( (a[j]-i)*(a[j]-i) );
        res=min(res,temp);
    }

    printf("%d\n",res);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值