UVa11300 Spreading the Wealth
原题链接:
非常不错的一道题。以前做过一道水题与这道题类似,是一个从左往右的一个平均分配。而这道题是一个环状。
要点:列出方程组,消元变为单变量极值问题,利用中位数求出最短距离。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <stdio.h> 2 #include <string.h> 3 #include <algorithm> 4 #define N 1000005 5 typedef long long LL; 6 7 LL a[N], c[N]; 8 9 LL Labs(LL v){return v > 0 ? v : -v;} 10 11 int main() 12 { 13 int n, i; 14 LL sum, avg, ans; 15 while(scanf("%d", &n) == 1) 16 { 17 for(sum = 0, i = 1; i <= n; i ++) 18 { 19 scanf("%lld", &a[i]); 20 sum += a[i]; 21 } 22 23 avg = sum / n; 24 for(i = 1; i < n; i ++) 25 c[i] = c[i - 1] + a[i] - avg; 26 27 std::sort(c, c + n); 28 29 LL tmp = c[n / 2]; 30 for(ans = 0, i = 0; i < n; i ++) 31 ans += Labs(tmp - c[i]); 32 33 printf("%lld\n", ans); 34 } 35 return 0; 36 }