Salem gave you n sticks with integer positive lengths a1,a2,…,an.c++
For every stick, you can change its length to any other positive integer length (that is, either shrink or stretch it). The cost of changing the stick's length from a to b is |a−b|, where |x| means the absolute value of x.ide
A stick length ai is called almost good for some integer t if |ai−t|≤1.atom
Salem asks you to change the lengths of some sticks (possibly all or none), such that all sticks' lengths are almost good for some positive integer t and the total cost of changing is minimum possible. The value of t is not fixed in advance and you can choose it as any positive integer.spa
As an answer, print the value of t and the minimum cost. If there are multiple optimal choices for t, print any of them.code
The first line contains a single integer n (1≤n≤1000) — the number of sticks.orm
The second line contains n integers ai (1≤ai≤100) — the lengths of the sticks.xml
Print the value of t and the minimum possible cost. If there are multiple optimal choices for t, print any of them.blog
3 10 1 4
3 7
5 1 1 2 2 3
2 0
In the first example, we can change 1 into 2 and 10 into 4 with cost |1−2|+|10−4|=1+6=7 and the resulting lengths [2,4,4]are almost good for t=3.ip
In the second example, the sticks lengths are already almost good for t=2, so we don't have to do anything.ci
1 #include <bits/stdc++.h> 2 #include <cstdio> 3 4 using namespace std; 5 6 int n; 7 int a[1005]; 8 int sum=0; 9 10 int cal(int k){ 11 int res=0; 12 for(int i=0;i<n;i++){ 13 if(abs(a[i]-k)>1){ 14 res+=(abs(a[i]-k)-1); 15 } 16 } 17 return res; 18 } 19 20 int main() 21 { 22 int minn=99999999; 23 int maxx=0; 24 scanf("%d",&n); 25 for(int i=0;i<n;i++){ 26 scanf("%d",&a[i]); 27 sum+=a[i]; 28 minn=a[i]<minn?a[i]:minn; 29 maxx=a[i]>maxx?a[i]:maxx; 30 } 31 int r1=1; 32 int cost=99999999; 33 int now=0; 34 for(int i=minn;i<=maxx;i++){ 35 now=cal(i); 36 if(now<cost){ 37 r1=i; 38 cost=now; 39 } 40 } 41 printf("%d %d\n",r1,cost); 42 /* 43 int r1=sum/n; 44 int r2=r1+1; 45 int _r1=cal(r1,a); 46 int _r2=cal(r2,a); 47 48 if(_r1<_r2){ 49 printf("%d %d\n",r1,_r1); 50 }else{ 51 printf("%d %d\n",r2,_r2); 52 } 53 */ 54 55 return 0; 56 }