いっしょ / 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≦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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?