A. Fox and Number Game

来源:互联网 发布:java 发联机报文 编辑:程序博客网 时间:2024/05/16 17:22

time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Fox Ciel is playing a game with numbers now.

Ciel has n positive integers: x1x2, ..., 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.

Input

The first line contains an integer n (2 ≤ n ≤ 100). Then the second line contains n integers: x1x2, ..., xn (1 ≤ xi ≤ 100).

Output

Output a single integer — the required minimal sum.

Sample test(s)
input
21 2
output
2
input
32 4 6
output
6
input
212 18
output
12
input
545 12 27 30 18
output
15
Note

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 - x2x2 = 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;}


0 0