[Basic Course on Acwing Algorithm] Chapter 6 Greedy-Absolute Value Inequality-104. Warehouse location selection

Question: 104. Warehouse location selection - AcWing question bank

Idea:

  1. All points sorted

  2. When there is an even number, the minimum value can be obtained by taking the warehouse between the two middle points.

  3. When there is an odd number, just get the median from the warehouse.

Proof method:

Why is the above approach correct? -- Absolute value inequality is used:

        f(x) =|xn - x| + |xn-1 - x| + |xn-2 - x| + ... |x1-x|

        >= |xn - x1| + |xn-1 - x2| + ...

        The minimum value is xn - x1 + xn-1 - x2 + ...

        The odd number is the median, the even number is between the two middle points, or the median (a[n/2]). In summary, whether it is an odd number or an even number, all warehouses can be calculated Take the median and get the minimum value

Solution: AcWing 104. Warehouse location selection (one question per day during winter vacation) - AcWing

If you don’t understand, you can watch the video, it’s very clear

Code:

#include <iostream>
#include <algorithm>
//贪心 绝对值不等式 104.货仓选址
using namespace std;

const int N = 100010;

int n;
int a[N];

int main()
{
    scanf("%d", &n);//输入点个数
    for(int i = 0; i < n; i++) scanf("%d", &a[i]);//输入点坐标

    sort(a, a + n);

    int res = 0;
    for(int i = 0; i < n; i++) res += abs(a[i] - a[n / 2]);//循环n个, |a[i] - 中位数|

    printf("%d\n", res);
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_65293439/article/details/128462654