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++14 (GCC 5.4.1) (judge verdict: Wrong Answer)

#include <bits/stdc++.h>
using namespace std;

const int N = 2005;

int n;
int a[N];
int dir[N][N];
vector<int> G[N];
int mn_comp[N];
int par[N];
bool inQueue[N];
int deg[N];
vector<int> ans;

int anc(int p) { return p == par[p] ? p : par[p] = anc(par[p]); }
void join(int p, int q) { par[anc(p)] = anc(q); }

int main() {
	ios_base::sync_with_stdio(false); cin.tie(0);
	cin >> n;
	for (int i = 1; i <= n; ++i) cin >> a[i];
	sort(a + 1, a + n + 1);
	
	for (int i = 1; i <= n; ++i) par[i] = i; // for DSU
	for (int i = 1; i <= n; ++i) {
		for (int j = i + 1; j <= n; ++j) if (__gcd(a[i], a[j]) != 1) {
			dir[i][j] = dir[j][i] = 1;
			join(i, j);
		}
	}

	for (int i = 1; i <= n; ++i) {
		int p = anc(i);
		if (mn_comp[p] == 0) mn_comp[p] = i; else mn_comp[p] = min(mn_comp[p], i);
	}

	for (int i = 1; i <= n; ++i) if (i == anc(i)) { // new component
		int start = mn_comp[i];
		priority_queue <int, vector<int>, greater<int> > q; 
		q.push(start);

		while(!q.empty()) {
			int u = q.top(); q.pop();
			for (int j = 1; j <= n; ++j) if (dir[u][j]) {
				dir[j][u] = 0; if (!inQueue[j]) inQueue[j] = true, q.push(j);
			}
		}
	}

	for (int i = 1; i <= n; ++i) {
		for (int j = 1; j <= n; ++j) if (dir[i][j]) G[i].push_back(j), ++deg[j];
	}
	
	memset(inQueue, 0, sizeof inQueue);
	priority_queue <int> q;
	for (int i = 1; i <= n; ++i) if (deg[i] == 0) q.push(i);

	while(!q.empty()) {
		int u = q.top(); q.pop(); inQueue[u] = true;
		ans.push_back(u);
		for (int v : G[u]) if (!inQueue[v]) {
			--deg[v];
			if (deg[v] == 0) q.push(v);
		}
	}

	for (int u : ans) printf("%d ", a[u]); printf("\n");
}