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>
#define FOR(i,a,b) for (register int i=(a);i<=(b);i++)
#define For(i,a,b) for (register int i=(a);i>=(b);i--)
#define mem(i,j) memset(i,j,sizeof(i))
#define GO(u) for (register int j=f[u];j!=-1;j=nxt[j])
#define fi first
#define se second
#define pii pair<int,int>
#define MP make_pair
#define pb push_back
using namespace std;
typedef long long ll;
const int N=2020;
int n,a[N],vis[N],l[N],r[N],line[N][N],cnt=0,ans[N];
vector<int> vec[N];
priority_queue <pii> q;
inline int read()
{
	int x=0,f=1;
	char c=getchar();
	while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();}
	while (c>='0'&&c<='9') {x=(x<<1)+(x<<3)+c-'0';c=getchar();}
	return f*x;
}
inline void write(int x)
{
	if (x<0) putchar('-'),x=-x;
	if (x>9) write(x/10);
	putchar(x%10+'0');
	return;
}
inline int GCD(int x,int y)
{
	if (!y) return x;
	if (x<y) return GCD(y,x);
	return GCD(y,x%y);
}
inline void dfs(int u)
{
	vis[u]=1;
	line[cnt][++r[cnt]]=u;
	FOR(i,0,(int)vec[u].size()-1)
	{
		int v=vec[u][i];
		if (vis[v]) continue;
		dfs(v);
	}
	return;
}
int main()
{
	n=read();
	FOR(i,1,n) a[i]=read();
	FOR(i,1,n) FOR(j,1,n) if (i!=j) if (GCD(a[i],a[j])>1) vec[i].pb(j);
	FOR(i,1,n) sort(vec[i].begin(),vec[i].end());
	FOR(i,1,n) if (!vis[i]) {cnt++;l[cnt]=1,r[cnt]=0;dfs(i);}
	FOR(i,1,cnt) q.push(MP(line[i][l[i]],i));
	while (q.size())
	{
		pii tmp=q.top();
		q.pop();
		ans[++ans[0]]=tmp.fi;
		if (l[tmp.se]<=r[tmp.se])
		{
			l[tmp.se]++;
			q.push(MP(line[tmp.se][l[tmp.se]],tmp.se));
		}
	}
	FOR(i,1,n) ans[i]=a[ans[i]];
	FOR(i,1,n) write(ans[i]),putchar(' ');
	return 0;
}