AcWing 122. 糖果传递(数学分析+贪心)

Problem

这题还真是个不折不扣的数学化简问题。。
假设每个小孩子给右边的孩子xi个糖果(负数就是反过来给)

在第一个人中,一定会向第二个人拿糖果或者向第二个人给糖果,其数量为|A[1] - avg|,更新A[2]

在第二个人中,一定会向第三个人拿糖果或者向第三个人给糖果,其数量为|A[2] - avg|,更新A[3]

在第(n - 1)个人中,一定会向第n个人拿糖果或者向第n个人给糖果,其数量为|A[n - 1] - avg|,更新A[n]
即使在某个时刻有某个A[i]被减为负数也没关系,因为接下来A[i]会从A[i + 1]处拿

最后化简成货仓取址的问题。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;

class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static int N = 1000010, n;
    static long a[] = new long[N];
    static long res, ave;

    public static void main(String[] args) throws Exception {
        n = Integer.parseInt(br.readLine());
        for (int i = 1; i <= n; i++) {
            a[i] = Long.parseLong(br.readLine());
            ave += a[i];
        }

        ave /= n;

        for (int i = n; i > 1; i--) a[i] = ave - a[i] + a[i + 1];

        a[1] = 0;

        Arrays.sort(a, 1, n + 1);

        for (int i = 1; i <= n; i++) res += Math.abs(a[i] - a[n + 1 >> 1]);

        pw.print(res);
        pw.flush();
        pw.close();
        br.close();

    }
}
发布了167 篇原创文章 · 获赞 3 · 访问量 3398

猜你喜欢

转载自blog.csdn.net/qq_43515011/article/details/104696808