zoukankan      html  css  js  c++  java
  • 【BZOJ1045】[HAOI2008]糖果传递

    【BZOJ1045】[HAOI2008]糖果传递

    题面

    bzoj

    洛谷

    题解

    根据题意,我们可以很容易地知道最后每个人的糖果数(ave)

    设第(i)个人给第(i-1)个人(X_i)个糖果((i=1)则表示第1个人个第(n)个人,(X_i<0)则表示(i-1)(i)糖果(-X_i))

    由题,第一个人最后(A_1-X_1+X_2=ave)

    (Rightarrow x_2=ave-A_1+X_1)(设(C_1=A_1-ave),下面同理)

    (Rightarrow x_2=x_1-C_1)

    (Rightarrow x_3=x_1-C_2)

    (......)

    (Rightarrow x_n=x_1-C_{n-1})

    题目变为求(x_1)使(|x1|+|x1-c_1|+|x_1-c_2|+...+|x_1-c_{n-1}|)最小

    可知(x_1)取中间值时原式最小

    代码

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <cstring> 
    #include <cmath> 
    #include <algorithm>
    using namespace std;
    typedef long long ll; 
    const int MAX_N = 1e6 + 5; 
    int N;
    ll A[MAX_N], C[MAX_N], tot, M; 
    int main () {
    	while (scanf("%d", &N) != EOF) {
    		tot = 0;
    		for (int i = 1; i <= N; i++) { scanf("%lld", &A[i]); tot += A[i]; }
    		M = tot / N; 
    		C[0] = 0; 
    		for (int i = 1; i < N; i++) C[i] = C[i - 1] + A[i] - M; 
    		sort(&C[0], &C[N]);
    		ll mid = C[N / 2], ans = 0; 
    		for (int i = 0; i < N; i++) ans += abs(mid - C[i]); 
    		printf("%lld
    ", ans); 
    	} 
    	return 0; 
    } 
    
  • 相关阅读:
    Multithread 之 synchronous
    【转】windows exe文件加载
    Transparent 之 SetLayeredWindowAttributes
    任意目录运行vs2005 tools
    【转】volatile
    Qt1命令行编译
    初识Qt
    typedef使用一
    Qthello
    源文件包含源文件
  • 原文地址:https://www.cnblogs.com/heyujun/p/10178217.html
Copyright © 2011-2022 走看看