AcWing每日一题--货仓选址

题目:https://www.acwing.com/problem/content/106/

贪心,将商店从0~n-1编号

   如果n是奇数,将货仓放在第n/2个商店上就可以了

   如果n是偶数,将货仓放在n/2-1和n/2商店之间就可以了

 1 #include<iostream>
 2 #include<cmath>
 3 #include<algorithm>
 4 using namespace std;
 5 const int N=100010;
 6 bool cmp(int a,int b){
 7     return a<b;
 8 }
 9 int a[N];
10 int main(void){
11     int n;
12     cin>>n;
13     for(int i=0;i<n;i++){
14         cin>>a[i];
15     }
16     sort(a,a+n,cmp);
17     long long res=0;
18     if(n%2){
19         int t=a[n/2];
20         for(int i=0;i<n;i++){
21             res+=abs(a[i]-t);
22         }
23     }else{
24         int t=(a[n/2]+a[n/2-1])/2;
25         for(int i=0;i<n;i++){
26             res+=abs(a[i]-t);
27         }
28     }
29     cout<<res;
30     return 0;
31 }

 

posted on 2021-01-15 14:38  greenofyu  阅读(113)  评论(0)    收藏  举报