codeforces 389A. Fox and Number Game

男娘i 2022-08-10 06:10 136阅读 0赞

题目链接[CF 389A.] (http://codeforces.com/problemset/problem/389/A):
题目描述:
A. Fox and Number Game
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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 n integers: x1, x2, …, xn (1 ≤ xi ≤ 100).

Output
Output a single integer — the required minimal sum.

Sample test(s)
input
2
1 2
output
2
input
3
2 4 6
output
6
input
2
12 18
output
12
input
5
45 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 - x2, x2 = x2 - x1.

言简意赅:
此题题意为可以连续多次利用ai=ai-aj,直到把ai中的每一个数变成最小且相等时,既满足题意中的条件不再能进行操作了,所以可以借助于直接暴力的代码进行实现.

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <algorithm>
  4. using namespace std;
  5. int a[105];
  6. int main()
  7. {
  8. int n;
  9. int flag;
  10. while(scanf("%d",&n)!=EOF)
  11. {
  12. flag=0;
  13. for(int i=0;i<n;i++)
  14. {
  15. scanf("%d",&a[i]);
  16. }
  17. while(1)
  18. {
  19. sort(a,a+n,greater<int>());
  20. flag=0;
  21. for(int i=0;i<n-1;i++)
  22. {
  23. if(a[i]>a[i+1])
  24. a[i]=a[i]-a[i+1];
  25. else flag++;
  26. }
  27. if(flag==n-1)
  28. break;
  29. }
  30. printf("%d\n",n*a[0]);
  31. }
  32. return 0;
  33. }

当然此题的本意可以简化为要去求解所有数的最大公约数的问题,代码实现如下:

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <algorithm>
  4. using namespace std;
  5. int gcd(int a,int b)
  6. {
  7. if(!b)
  8. return a;
  9. else return gcd(b,a%b);
  10. }
  11. int a[105];
  12. int main()
  13. {
  14. int n;
  15. int k;
  16. while(scanf("%d",&n)!=EOF)
  17. {
  18. for(int i=0; i<n; i++)
  19. {
  20. scanf("%d",&a[i]);
  21. }
  22. k=gcd(a[0],a[1]);
  23. for(int i=2; i<n; i++)
  24. {
  25. k=gcd(k,a[i]);
  26. }
  27. printf("%d\n",n*k);
  28. }
  29. return 0;
  30. }

如果代码还不能A掉,那就不能去睡觉。

发表评论

表情:
评论列表 (有 0 条评论,136人围观)

还没有评论,来说两句吧...

相关阅读

    相关 CodeForces 510C Fox And Names

    一道拓扑排序题!! 注意判断各种情况,两个字符串比较的时候,从左向右开始比较,当出现不同的字母后,不再向后比较。一个是另一个的前缀,那么长的在后面。 当给出的顺序出现环的时