题目链接:http://codeforces.com/problemset/problem/582/A
网上很多题解,就不说了,直接贴代码= =
官方题解:
http://codeforces.com/blog/entry/20692
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <map>
#include <vector>
using namespace std; const int maxn = + ;
map<int, int> cnt;
vector<int> ans;
int a[maxn*maxn]; int GCD(int a, int b)
{
return b == ? a : GCD(b, a%b);
} int main()
{
int n;
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif // ONLINE_JUDGE while (scanf("%d", &n) != EOF) {
ans.clear();
for (int i = ; i < n*n; i++) {
scanf("%d", &a[i]);
cnt[a[i]]++;
} sort(a, a+n*n);
for (int i = n*n-; i >= ; i--) {
if (cnt[a[i]] <= ) {
continue;
}
cnt[a[i]]--; for (int j = ; j < ans.size(); j++) {
cnt[GCD(ans[j], a[i])] -= ;
}
ans.push_back(a[i]);
}
for (int i = ; i < ans.size(); i++) {
cout << ans[i] << (i == ans.size()- ? '\n' : ' ');
}
}
return ;
}
官方解法代码(个人比较喜欢这个)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
using namespace std; const int maxn = + ; map<int, int> cnt;
int ans[maxn]; int gcd(int a, int b)
{
return b == ? a : gcd(b, a % b);
} int main()
{
int a, n; #ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif // ONLINE_JUDGE while (scanf("%d", &n) != EOF) {
for (int i = ; i < n*n; i++) {
scanf("%d", &a);
cnt[-a]++; // 为了将数组从大到小排序
} int pos = n-;
for (map<int, int>::iterator mp = cnt.begin(); mp != cnt.end(); ++mp) {
int x = -mp->first; while (mp->second) { // 当次数还有的时候
ans[pos] = x;
--mp->second;
for (int i = pos+; i < n; i++) {
cnt[-gcd(ans[i], x)] -= ;
}
pos--;
} }
for (int i = ; i < n; i++) {
printf("%d%c", ans[i], (i == n- ? '\n' : ' '));
}
}
return ;
}