本文最后更新于2021年11月3日,已超过 1 个月没更新!

第六讲 贪心

绝对值不等式

货舱选址

import java.util.*;
import java.io.*;

public class Main {
    public static void main (String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        int n = Integer.parseInt(br.readLine());
        String[] strs = br.readLine().split(" ");
        int[] stores = new int[n];
        for (int i = 0; i < n; ++ i) stores[i] = Integer.parseInt(strs[i]);

        Arrays.sort(stores);
        int pos = stores[n / 2];
        int ans = 0;
        for (int s : stores) {
            ans += Math.abs(pos - s);
        }
        bw.write(ans + "\n");
        bw.close();
        br.close();
    }
}

Try and fail, but don't fail to try.