uva 11300 Spreading the wealth

来源:互联网 发布:常州地球人软件 编辑:程序博客网 时间:2024/05/17 07:22

题目链接:点击打开链接

题目大意:圆桌旁坐着n个人,每个人有一定数量的金币,金币总数能被n整除.每个人需要给相邻的人一些金币,使得最后每个人手中的金币数目一样.你需要求出转手金币数量的最小值.

思路:数学分析 转化为求数轴上到n个点距离总和最小的点

分析:设每个人开始有Ai个金币.每个人最终拥有的金币数设为M.设xi为第i个人给第i-1个人的金币数(x1表示第1个人给第n个人的金币数).那么可以列出下列方程:

对于第一个人: A1-x1+x2 = M -> x2 = x1-(A1-M) = x1 - C1(设C1 = A1 - M,下面类似)

对于第二个人: A2-x2+x3 = M -> x3 = x2-(A2-M) = x1 - C1 - (A2 - M) = x1 - C2

对于第三个人: A3-x3+x4 = M -> x4 = x3-(A3-M) = x1 - C1 - C2 - (A3 - M) = x1 - C3

...

最后,相当于求|x1| + |x1-C1| + |x1-C2| + |x1-C3| +... + |x1-Cn-1|的最小值,转化为求数轴上到n个点(C1,C2,C3...)距离总和最小的点,即这些点的中位数.

代码:

#include <cstdio>#include <algorithm>#include <cmath>using namespace std;const int maxn = 1000001 + 5;long long coins[maxn];long long coin_diff[maxn];int main(){int n;long long sum, average;int i;while (scanf("%d", &n) != EOF){sum = 0;for (i = 0; i < n; i++) {scanf("%lld", &coins[i]);sum += coins[i];}average = sum / n;long long temp = 0;coin_diff[0] = 0;for (i = 1; i < n; i++) {temp += coins[i-1];coin_diff[i] = temp - average * i;}sort(coin_diff, coin_diff + n);long long middle = coin_diff[n / 2];sum = 0;for (i = 0; i < n; i++)sum += abs(middle - coin_diff[i]);printf("%lld\n", sum);}return 0;}




原创粉丝点击