{"title":"题目描述","description":"给定整数序列 \na , 你要对每一个 \na \i \ 进行恰好一次修改操作, 使得 \na 中每个元素都相等, 且都为整数.\n\n把 \nx 变成 \ny 花费的代价是 (\nx−\ny)\ 2 , 求最小代价.\n\n注意, 可以把 \nx 变成 \nx .","keywords":"算法题, C++, 整数序列, 最小代价, 优化, 代码实现, 详细解析","content":"#include #include #include #include using namespace std;

int main() { int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a.begin(), a.end()); int median = a[n/2]; int cost = 0; for (int i = 0; i < n; i++) { cost += pow(a[i] - median, 2); } cout << cost << endl; return 0; }"}

C++ 算法题:整数序列修改最小代价 - 详细解析及代码实现

原文地址: https://www.cveoy.top/t/topic/pXxD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录