分金币(Spreading the Wealth, UVa 11300)【JAVA算法实现】
2014-11-22 09:10
363 查看
题目描述
圆桌旁坐着n个人,每人有一定数量的金币,金币总数能被n整除。每个人可以给他左右相邻的人一些金币,最终使得每个人的金币数目相等。你的任务是求出被转手的金币数量的最小值。比如,n=4,且4个人的金币数量分别为1,2,5,4时,只需转移4枚金币(第3个人给第2个人两枚金币,第2个人和第4个人分别给第1个人1枚金币)即可实现每人手中的金币数目相等。
输入格式
输入包含多组数据。每组数据第一行为整数n(n≤1 000 000),以下n行每行为一个整数,按逆时针顺序给出每个人拥有的金币数。输入结束标志为文件结束符(EOF)。
输出
对于每组数据,输出被转手金币数量的最小值。输入保证这个值在64位无符号整数范围内。
样例输入
3100
100
100
4
1
2
5
4
样例输出
04
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String arg[]) {
Scanner cin = new Scanner(System.in);
final int maxn = 1000000 + 10;
while (cin.hasNext()) {
int n = cin.nextInt(), tot = 0, C[] = new int[maxn], A[] = new int[maxn];
for (int i = 1; i <=n; i++) {
A[i] = cin.nextInt();
tot += A[i];
}
tot = tot / n;
for (int i = 1; i < n; i++) {
C[i] = A[i] + C[i - 1] - tot;
}
Arrays.sort(C, 0, n);
int x1 = C[n / 2], ans = 0;
for (int i = 0; i < n; i++) {
ans += Math.abs(C[i] - x1);
}
System.out.println(ans);
}
}
}
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String arg[]) {
Scanner cin = new Scanner(System.in);
final int maxn = 1000000 + 10;
while (cin.hasNext()) {
int n = cin.nextInt(), tot = 0, C[] = new int[maxn], A;
for (int i = 1; i <=n; i++) {
C[i] = C[i-1]+cin.nextInt();
}
C
/= n;
for (int i = 1; i <= n; i++) {
C[i] -= i*C
;
}
Arrays.sort(C, 0, n);
int x1 = C[n / 2], ans = 0;
for (int i = 0; i < n; i++) {
ans += Math.abs(C[i] - x1);
}
System.out.println(ans);
}
}
}
相关文章推荐
- [ACM_几何] UVA 11300 Spreading the Wealth [分金币 左右给 最终相等 方程组 中位数]
- UVA 11300 Spreading the Wealth 分金币
- UVa11300 - Spreading the Wealth (分金币)
- 分金币(Spreading the Wealth,UVa 11300)
- 分金币(Spreading the Wealth,UVa 11300,中位数)
- [训练指南] 第一章 例题3 分金币 (Spreading the wealth,Uva 11300)
- UVa 11300 Spreading the Wealth 分金币
- (uva 11300)分金币(Spreading the Wealth)
- UVa11300 Spreading the Wealth 分金币
- UVa11300 - Spreading the Wealth (分金币)
- 中位数-分金币(Spreading the Wealth, UVa 11300)
- uva11300 - Spreading the Wealth(分金币)
- UVa 11300 Spreading the Wealth 分金币 (中位数)
- uva 11300 - Spreading the Wealth
- uva 11300 - Spreading the Wealth(思维)
- UVa 11300 Spreading the Wealth 数学题
- UVA11300——Spreading the Wealth (贪心+建模)
- UVA11300 Spreading the Wealth
- UVA 题目11300 - Spreading the Wealth
- UVA 11300 Spreading the Wealth (数学推导 中位数)