Problem:
Score : 1600 points

Problem Statement

There are N integers written on a blackboard. The i-th integer is A_i.

Takahashi and Aoki will arrange these integers in a row, as follows:

First, Takahashi will arrange the integers as he wishes.

Then, Aoki will repeatedly swap two adjacent integers that are coprime, as many times as he wishes.

We will assume that Takahashi acts optimally so that the eventual sequence will be lexicographically as small as possible, and we will also assume that Aoki acts optimally so that the eventual sequence will be lexicographically as large as possible.
Find the eventual sequence that will be produced.

Constraints

1 ≦ N ≦ 2000

1 ≦ A_i ≦ 10^8

Input

The input is given from Standard Input in the following format:

N
A_1 A_2 … A_N

Output

Print the eventual sequence that will be produced, in a line.

Sample Input 1

5
1 2 3 4 5

Sample Output 1

5 3 2 4 1

If Takahashi arranges the given integers in the order (1,2,3,4,5), they will become (5,3,2,4,1) after Aoki optimally manipulates them.

Sample Input 2

4
2 3 4 6

Sample Output 2

2 4 6 3

Solution in C++ (GCC 9.2.1) (judge verdict: Wrong Answer)

#include <bits/stdc++.h>

#define F first
#define S second
#define pb push_back
#define all(x) x.begin(), x.end()

using namespace std;

typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;

const int N = 2000 + 10;
const int MOD = 1000000007;
const int LOG = 20;
const int INF = 1000000010;
const int delta = 11353;

int n;
vi G[N], a;
map<int, int> mp;
int mark[N];
int mark2[N];

void DFS(int v){
	mark[v] = 1;
	for (auto u:G[v]){
		if ((mark[u] == 0) && (mark2[u] == 0)){
			DFS(u);
		}
	}
}
int GCD(int x, int y){
	if (x == 0 || y == 0) return (x + y);
	if (x == 1 || y == 1) return 1;
	if (x < y) swap(x, y);
	return GCD(y, x % y);
}

int32_t main(){
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin >> n;
	for (int i = 1; i <= n; i++){
		int x;
		cin >> x;
		mp[x] ++;
		a.pb(x);
	}
	sort(all(a));
	a.resize(unique(all(a)) - a.begin());
	for (int i = 0; i < a.size(); i++) for (int j = 0; j < i; j++) if (GCD(a[i], a[j]) != 1){
		G[i].pb(j), G[j].pb(i);
	}
	//cout << GCD(7, 11) << '\n';
	vi ans;
	int last = 0;
	for (int i = 0; i < a.size(); i++){
		int ki;
		memset(mark, 0, sizeof mark);
		if (i == 0){
			int mx = 0;
			for (int j = 0; j < a.size(); j++) if (!mark[j]) mx = j, DFS(j);
			mark2[mx] = 1;
			ans.pb(a[mx]);
			//cout << a[mx] << endl;
			last = mx;
		}else{
			sort(all(G[last]));
			int mx = 0;
			for (auto u:G[last]){
				if ((mark2[u] == 0) && (mark[u] == 0)) mx = u, DFS(u);
			}
			for (int j = 0;  j < a.size(); j++){
				if ((mark[j] == 0) && (mark2[j] == 0)) mx = max(j, mx), DFS(j);
			}
			mark2[mx] = 1;
			ans.pb(a[mx]);
			last = mx;
			//cout << a[mx] << endl;
		}
	}
	for (auto u:ans){
		for (int i = 0; i < mp[u]; i++) cout << u << ' ';
	}
	return 0;
}