贪心 - 绝对值不等式

107 阅读1分钟

绝对值不等式

  • 问题背景

在一条数轴上有 N 家商店,它们的坐标分别为 A1∼AN

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

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

  • 策略
    • 从小到大排序,选择中位数

练习

01 货仓选址

  • 题目

Snipaste_2023-04-06_20-12-44.png

  • 题解
import java.io.*;
import java.util.*;

public class Main {
    public static final int N = 100010;
    public static int[] a = new int[N];
    public static int n, choice;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
        n = Integer.parseInt(br.readLine());
        String[] str1 = br.readLine().split(" ");
        for (int i = 1; i <= n; i++) {
            a[i] = Integer.parseInt(str1[i - 1]);
        }

        Arrays.sort(a, 1, n + 1);
        if (n % 2 == 0) {
            choice = (a[n / 2] + a[n / 2 + 1]) / 2;
        } else {
            choice = a[(n + 1) / 2];
        }
        
        int res = 0;
        for (int i = 1; i <= n; i++) {
            res += Math.abs(choice - a[i]);
        }
        pw.println(res);
        pw.close();
        br.close();
    }
}