Codeforces Round #533(Div. 2) A.Salem and Sticks
链接:https://codeforces.com/contest/1105/problem/A
题意:
给n个数,找到一个数t使i(1-n)∑|ai-t| 最小。
ai-t 差距1 以内都满足
思路:
暴力,枚举。
代码:
#include <bits/stdc++.h> using namespace std; typedef long long LL; const int MAXN = 1000+5; int a[MAXN]; int main() { int n; scanf("%d",&n); for (int i = 1;i<=n;i++) scanf("%d",&a[i]); int t,cost = 1e6; for (int i = 1;i<=100;i++) { int key = i; int sum = 0; for (int j = 1;j<=n;j++) { if (a[j] < key-1) sum += abs(a[j] - (key-1)); if (a[j] > key+1) sum += abs(a[j] - (key+1)); } if (sum < cost) { cost = sum; t = key; } } printf("%d %d\n",t,cost); return 0; }