Advanced guide to algorithm competition---0x05 (sorting) warehouse location

Topic

Insert picture description here

answer

Warehouse location : greedy classic problem, the median is the optimal location of the warehouse

Insert picture description here
Proof : As shown in the figure, we can deduce the formula and deform it. In order to minimize d, then let >= become equal to the optimal solution. We find that for (|x1-x|+|xn-x|), there is only x In the middle of x1-xn (the position of 2 in the figure) becomes xn-x1, which is the optimal solution. Looking at the second formula, (|x2-x|+|xn-1-x|), the optimal position is also in the middle of x2—xn-1, we find that these two optimal positions do not conflict, so for All formulas are satisfied, then we find that this middle position is the middle of all warehouses, which is the median of warehouse positions.

The problem of the number of warehouses : For n is odd, then there is only one median, and there is only one optimal position of the warehouse; for n is even, then there are two medians, a[n/2] and a[n /2-1], then the number of warehouses is a[n/2]-a[n/2-1]+1 (including the median between the median is the optimal position of the warehouse)

Code

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>

using namespace std;
typedef long long ll;
const int N=1e5+10;

int n;
int a[N];


int main(){
    
    


    std::ios ::sync_with_stdio(false);
    std::cin.tie(nullptr);

    cin>>n;

    for(int i=0;i<n;i++) cin>>a[i];

    sort(a,a+n);

    int res=0;
    for(int i=0;i<n;i++) res+=abs(a[i]-a[n/2]);

    cout<<res<<endl;


    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/114597178