codeforces 582A. GCD Table 解题报告

题目链接:http://codeforces.com/problemset/problem/582/A

  网上很多题解,就不说了,直接贴代码= =

  官方题解:

  http://codeforces.com/blog/entry/20692

  

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <algorithm>
 6 #include <map>
 7 #include <vector>
 8 using namespace std;
 9 
10 const int maxn = 500 + 5;
11 map<int, int> cnt;
12 vector<int> ans;
13 int a[maxn*maxn];
14 
15 int GCD(int a, int b)
16 {
17     return b == 0 ? a : GCD(b, a%b);
18 }
19 
20 int main()
21 {
22     int n;
23     #ifndef ONLINE_JUDGE
24         freopen("in.txt", "r", stdin);
25     #endif // ONLINE_JUDGE
26 
27     while (scanf("%d", &n) != EOF) {
28         ans.clear();
29         for (int i = 0; i < n*n; i++) {
30             scanf("%d", &a[i]);
31             cnt[a[i]]++;
32         }
33 
34         sort(a, a+n*n);
35         for (int i = n*n-1; i >= 0; i--) {
36             if (cnt[a[i]] <= 0) {
37                 continue;
38             }
39             cnt[a[i]]--;
40 
41             for (int j = 0; j < ans.size(); j++) {
42                 cnt[GCD(ans[j], a[i])] -= 2;
43             }
44             ans.push_back(a[i]);
45         }
46         for (int i = 0; i < ans.size(); i++) {
47             cout << ans[i] << (i == ans.size()-1 ? '\n' : ' ');
48         }
49     }
50     return 0;
51 }

 

官方解法代码(个人比较喜欢这个)

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <map>
 6 using namespace std;
 7 
 8 const int maxn = 500 + 5;
 9 
10 map<int, int> cnt;
11 int ans[maxn];
12 
13 int gcd(int a, int b)
14 {
15     return b == 0 ? a : gcd(b, a % b);
16 }
17 
18 int main()
19 {
20     int a, n;
21 
22     #ifndef ONLINE_JUDGE
23         freopen("in.txt", "r", stdin);
24     #endif // ONLINE_JUDGE
25 
26     while (scanf("%d", &n) != EOF) {
27         for (int i = 0; i < n*n; i++) {
28             scanf("%d", &a);
29             cnt[-a]++;  // 为了将数组从大到小排序
30         }
31 
32         int pos = n-1;
33         for (map<int, int>::iterator mp = cnt.begin(); mp != cnt.end(); ++mp) {
34             int x = -mp->first;
35 
36             while (mp->second) {   // 当次数还有的时候
37                 ans[pos] = x;
38                 --mp->second;
39                 for (int i = pos+1; i < n; i++) {
40                     cnt[-gcd(ans[i], x)] -= 2;
41                 }
42                 pos--;
43             }
44 
45         }
46         for (int i = 0; i < n; i++) {
47             printf("%d%c", ans[i], (i == n-1 ? '\n' : ' '));
48         }
49     }
50     return 0;
51 }

 

转载于:https://www.cnblogs.com/windysai/p/4854825.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值