仓库选址

在一条数轴上有 NN 家商店,它们的坐标分别为 A1A1~ANAN。

现在需要在数轴上建立一家货仓,每天清晨,从货仓到每家商店都要运送一车商品。

为了提高效率,求把货仓建在何处,可以使得货仓到每家商店的距离之和最小。

输入格式

第一行输入整数N。

第二行N个整数A1A1~ANAN。

输出格式

输出一个整数,表示距离之和的最小值。

数据范围

1≤N≤1000001≤N≤100000

输入样例:

4
6 2 9 1

输出样例:

12

nth_element

时间复杂度O(n)

#include<iostream>
#include<algorithm>

using namespace std;

const int N=100010;
int a[N];

int main()
{
    int n;
    cin>>n;
    for(int i =0 ;i< n ; i++)
    {
        cin>>a[i];
    }
    nth_element(a, a + n / 2, a + n);  
    int mid=a[n/2];
    int res=0;
    for(int i=0 ;i <n; i++)
    {
        res+= abs(a[i]- mid);
    }
    cout<<res;
}

sort实现

|x|+|y|>=|x+y|

|x-a|+|x-b|>=|a-b|

时间复杂度nlogn

题目来源:acwing

#include<iostream>
#include<algorithm>

using namespace std;

const int N=100010;
int a[N];

int main()
{
    int n;
    cin>>n;
    for(int i =0 ;i< n ; i++)
    {
        cin>>a[i];
    }
    sort(a,a+n);
    int mid= a[n/2];
    
    int res=0;
    for(int i=0 ;i <n; i++)
    {
        res+= abs(a[i]- mid);
    }
    cout<<res;
}

猜你喜欢

转载自blog.csdn.net/weixin_42333573/article/details/105939790
今日推荐