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≦100Input
The input is given from Standard Input in the following format:
N
a1 a2 ... aNOutput
Print the minimum total cost to achieve Evi's objective.
Example
Sample Input 1
2
4 8Sample 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 3Sample 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 -100Sample 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;
}