The first question of 2021 winter vacation

104. Warehouse location

There are N stores on a number axis, and their coordinates are A1~AN.

Now it is necessary to build a warehouse on the number axis, and every morning, a truck of goods must be transported from the warehouse to each store.

In order to improve efficiency, find where to build the warehouse so that the sum of the distances from the warehouse to each store can be minimized.

Input format
Enter the integer N in the first line.

N integers A1~AN in the second line.

Output format
Output an integer that represents the minimum value of the sum of distances.

Data range
1≤N≤100000,
0≤Ai≤40000
Input example:

4
6 2 9 1

Sample output:

12

C++ code


/***
解决思路:
采用贪心算法(排序)
道理就是绝对值不等式问题
不管总的个数是奇数还是偶数 取中间即可 这样的距离值最小 n/2
**/
#include <iostream>
#include <algorithm>
using namespace std;
const int n=1000000;
int a[n];
int main(){
    
    
    int N;
    cin>>N;
    for(int i=0;i<N;i++ )
        cin>>a[i];
    sort(a,a+N);
    int dis=0;
    for(int i=0;i<N;i++)
        dis+=abs(a[i]-a[N/2]);
    cout<<dis<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/fxwentian/article/details/112442916