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 i and 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 nintegers: x1, x2, ..., xn (1 ≤ xi ≤ 100).
Output
Output a single integer — the required minimal sum.
Examples
2
1 2
2
3
2 4 6
6
2
12 18
12
5
45 12 27 30 18
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 - x2, x2 = x2 -x1.
题目意思:给你n个数,任意两个数直接,大数可以减去小数得到新的值再赋值给大数,如此反复,直到不出现大数和小数,即所有的数都相等。
解题思路:我看了看数据量很小,于是可以选择使用模拟的方法,将过程模拟了一下,其实能够发现这道题存在着规律,最后所有的数都会变成所有数的最大公约数。
上代码:
模拟法:
1 #include<stdio.h> 2 #include<algorithm> 3 using namespace std; 4 int main() 5 { 6 int n,i,j,ans; 7 int a[1010]; 8 scanf("%d",&n); 9 for(i=0; i<n; i++) 10 { 11 scanf("%d",&a[i]); 12 } 13 while(1) 14 { 15 sort(a,a+n); 16 if(a[n-1]==a[0])///互相减,直到都相等 17 { 18 break; 19 } 20 for(j=n-1; j>0; j--) 21 { 22 if(a[j]!=a[j-1]) 23 { 24 a[j]=a[j]-a[j-1]; 25 } 26 else 27 { 28 continue; 29 } 30 } 31 } 32 ans=a[0]*n; 33 printf("%d",ans); 34 return 0; 35 }
找到规律,使用GCD:
1 #include<stdio.h> 2 #include<algorithm> 3 using namespace std; 4 int gcd(int a,int b) 5 { 6 int r; 7 while(b>0) 8 { 9 r=a%b; 10 a=b; 11 b=r; 12 } 13 return a; 14 } 15 int main() 16 { 17 int i,k,n,ans; 18 int a[1010]; 19 scanf("%d",&n); 20 for(i=0;i<n;i++) 21 { 22 scanf("%d",&a[i]); 23 } 24 k=a[0]; 25 for(i=1;i<n;i++) 26 { 27 ans=gcd(k,a[i]); 28 k=ans; 29 } 30 printf("%d ",ans*n); 31 return 0; 32 }