zoukankan      html  css  js  c++  java
  • BZOJ 1045 题解

    1045: [HAOI2008] 糖果传递

    Time Limit: 10 Sec  Memory Limit: 162 MB
    Submit: 3502  Solved: 1623
    [Submit][Status][Discuss]

    Description

      有n个小朋友坐成一圈,每人有ai个糖果。每人只能给左右两人传递糖果。每人每次传递一个糖果代价为1。

    Input

      第一行一个正整数n<=987654321,表示小朋友的个数.接下来n行,每行一个整数ai,表示第i个小朋友得到的
    糖果的颗数.

    Output

      求使所有人获得均等糖果的最小代价。

    Sample Input

    4
    1
    2
    5
    4

    Sample Output

    4

    Solution

    刘汝佳蓝书上有具体推导过程,这里代码:

     1 /**************************************************************
     2     Problem: 1045
     3     User: shadowland
     4     Language: C++
     5     Result: Accepted
     6     Time:2056 ms
     7     Memory:16932 kb
     8 ****************************************************************/
     9  
    10 #include "bits/stdc++.h"
    11  
    12 using namespace std;
    13 typedef long long QAQ ;
    14 const int maxN = 1e6 + 1e3 ;
    15  
    16 QAQ long_long_INPUT ( ) {
    17         QAQ x = 0 , f = 1 ; char ch = getchar ( ) ;
    18         while ( ch < '0' || ch > '9' ) { if ( ch == '-' ) f = -1 ; ch = getchar ( ) ; }
    19         while ( ch >= '0' && ch <= '9' ) { x = ( x << 1 ) + ( x << 3 ) + ch - '0' ; ch = getchar ( ) ; }
    20         return x * f ;
    21 }
    22  
    23 long long A[ maxN ] , C[ maxN ] , tot , M ;
    24 int main ( ) {
    25         int n;
    26         n = long_long_INPUT ( ) ;
    27         tot = 0;
    28         for ( int i=1 ; i<=n ; ++i ){
    29                 A[ i ] = long_long_INPUT ( ) ;
    30                 tot += A[ i ] ;
    31         }
    32         M = tot / n;
    33         C[ 0 ] = 0;
    34          
    35         for(int i=1 ; i<n ; ++i ) C[ i ] = C[ i - 1 ] + A[ i ] - M ;
    36          
    37         sort( C, C + n ) ;
    38         long long x1 = C[ n / 2 ], ans = 0 ;
    39         for(int i=0 ; i<n ; ++i ) ans += abs ( x1 - C[ i ] ) ;
    40          
    41         cout << ans ;
    42  
    43         return 0;
    44 }
    View Code

    2016-10-14 23:56:18

    ()

  • 相关阅读:
    bzoj4423 [AMPPZ2013]Bytehattan
    bzoj3643 Phi的反函数
    hdu1024 Max Sum Plus Plus的另一种解法
    hdu1024 Max Sum Plus Plus
    bzoj3638 Cf172 k-Maximum Subsequence Sum
    bzoj3620 似乎在梦中见过的样子
    bzoj3667 Rabin-Miller算法
    bzoj3680 吊打XXX
    阿里Linux Shell脚本面试25个经典问答
    编程面试的10大算法概念汇总
  • 原文地址:https://www.cnblogs.com/shadowland/p/5962550.html
Copyright © 2011-2022 走看看