A. Fox and Number Game
来源:互联网 发布:java 发联机报文 编辑:程序博客网 时间:2024/05/16 17:22
Fox Ciel is playing a game with numbers now.
Ciel has n positive integers: x1, x2, ..., xn. She can do the following operation as many times as needed: select two different indexes iand j such that xi > xj hold, and then apply assignment xi = xi - xj. The goal is to make the sum of all numbers as small as possible.
Please help Ciel to find this minimal sum.
The first line contains an integer n (2 ≤ n ≤ 100). Then the second line contains n integers: x1, x2, ..., xn (1 ≤ xi ≤ 100).
Output a single integer — the required minimal sum.
21 2
2
32 4 6
6
212 18
12
545 12 27 30 18
15
In the first example the optimal way is to do the assignment: x2 = x2 - x1.
In the second example the optimal sequence of operations is: x3 = x3 - x2, x2 = x2 - x1.
解题说明:本题的要求是对一列数字中任意两个不同的数字进行减法操作,最后求出这一列数和的最小值。在数据规模小的时候完全可以用模拟的方法,每次迭代对数字排序,然后判断是否还存在不同的数字,如果不存在就得到结果,否则继续执行相减操作。
#include<iostream>#include<cstdio>#include<cmath>#include<cstdlib>#include <algorithm>#include<cstring>using namespace std;int main(){int n, i,j;int sum = 0;int answer=0;int a[102];scanf("%d", &n);for (i = 0; i < n; i++){scanf("%d", &a[i]);answer += a[i];}while (1){sum = 0;sort(a, a + n);if (a[n - 1] == a[0]){break;}for (j = n - 1; j>0; j--){if (a[j] != a[j - 1]){a[j] = a[j] - a[j - 1];}else{continue;}}for (i = 0; i < n; i++){sum += a[i];}answer = sum;}printf("%d\n", answer);return 0;}
显然,在数据规模变大时,这种做法很容易超时,经过对几个例子枚举后能够发现,只要有一大一小就肯定可以执行操作,所以到最后肯定剩下的数都是一样的,而且就是这些数的最大公约数。
#include <stdio.h>#include <string.h>const int N = 105;int n, num[N];int gcd(int a, int b) {if (b == 0) return a;return gcd(b, a % b);}int main () {scanf("%d", &n);for (int i = 0; i < n; i++) scanf("%d", &num[i]);int t = num[0];for (int i = 1; i < n; i++) t = gcd(t, num[i]);printf("%d\n", t * n);return 0;}
- A. Fox and Number Game
- Codeforces 389A Fox and Number Game
- 389-A Fox and Number Game
- CF 389A:Fox and Number Game
- codeforces A. Fox and Number Game
- CodeForces 389A Fox and Number Game
- codeforces 389A Fox and Number Game
- codeforces 389A. Fox and Number Game
- Fox and Number Game
- Codeforces Round #228 (Div. 2) A. Fox and Number Game
- Codeforces Round #228 (Div. 2)A.Fox and Number Game
- Codeforces Round #228 (Div. 2)A. Fox and Number Game
- Codeforces 389A Fox and Number Game(贪心)
- codeforecs Fox and Number Game
- L - Fox and Number Game
- codeforces Fox and Number Game
- vj --Fox and Number Game
- CF228A题Fox and Number Game
- 新产品入市调查方案设计
- 电脑桌面文件删除想找回怎么办
- 我啊
- ios -笔记
- Qemu-KVM管理
- A. Fox and Number Game
- 分享几篇非常棒的blog——关于java反射
- UI设计的素材收集
- android json解析及简单例子
- sscanf(格式化字符串输入)
- js 相对路径转为绝对路径
- Eval 方法
- OpenCV 学习笔记(1)显示图像
- Delphi7 导出Dbgrid数据到Excel 默认路径设置为我的文档