AOAPC:Chapter1Example3 (UVa 11300)

#include "bits/stdc++.h"
using namespace std;

const int Inf = 1000050;
long long init[Inf], cha[Inf];

int main(int argc, char const *argv[]) {
  int n;
  while (~scanf("%d", &n)) {
    long long tot = 0;
    for (size_t i = 1; i <= n; ++i) {
      scanf("%lld", &init[i]); tot += init[i];
    }
    long long ave = tot / n;
    cha[0] = 0;
    for (size_t i = 1; i <= n; i++)
      cha[i] = cha[i - 1] + init[i] - ave;
    sort (cha, cha + n);
    long long t = cha[n / 2], res = 0;
    for (size_t i = 0; i < n; ++i)
      res += abs(t - cha[i]);
    printf("%lld\n", res);
  }
  return 0;
}

你可能感兴趣的:(Algorithm,ACM-00)