11300 - Spreading the Wealth (UVA)

题目链接:Online Judge

按照刘汝佳的《算法竞赛入门经典——训练指南》。

#include 
#include 
#include 
#include 

int n;
std::vector vec;
long long tot, avg, ans;

int main(){
    while(scanf("%d", &n) == 1){
        vec.resize(n);
        tot = 0;
        for(int i = 0; i < n; ++i){
            scanf("%lld", &vec[i]);
            tot += vec[i];
        }
        avg = tot / n;
        std::vector c(n);
        c[0] = 0;
        for(int i = 1; i < n; ++i){
            c[i] = c[i - 1] + vec[i] - avg;
        }
        sort(c.begin(), c.end());
        long long mid = c[n / 2];
        ans = 0;
        for(int i = 0; i < n; ++i){
            ans += abs(c[i] - mid);
        }
        printf("%lld\n", ans);
    }
    return 0;
}

你可能感兴趣的:(UVA,算法)