Live2D

[AGC010E] Rearranging 题解

link

Solution

注意到不互质的数相对位置一定不改变,也就是说如果我们先手钦定了不互质的数之间的大小关系,那么后手一定是做一次 topo,每次选最大的出来。

那么,作为先手,我们肯定是选最小值当根,然后依次从小到大找能够当下一位的点连边,不过这里需要递归,而不能直接连,因为假如 \(1,2\)\(2,3\) 以及 \(1,3\) 都有边,那么我肯定 \(1\to 2\to 3\)\(1\to 3\) 以及 \(1\to 2\) 更优,因为后一种选择对于后者而言我们肯定是搞成 \(1,2,3\)

复杂度 \(\Theta(n^2)\)

Code

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

#define Int register int
#define MAXN 2005

template <typename T> inline void read (T &t){t = 0;char c = getchar();int f = 1;while (c < '0' || c > '9'){if (c == '-') f = -f;c = getchar();}while (c >= '0' && c <= '9'){t = (t << 3) + (t << 1) + c - '0';c = getchar();} t *= f;}
template <typename T,typename ... Args> inline void read (T &t,Args&... args){read (t);read (args...);}
template <typename T> inline void write (T x){if (x < 0){x = -x;putchar ('-');}if (x > 9) write (x / 10);putchar (x % 10 + '0');}
template <typename T> inline void chkmax (T &a,T b){a = max (a,b);}
template <typename T> inline void chkmin (T &a,T b){a = min (a,b);}

int n,s[MAXN],deg[MAXN];
bool vis[MAXN],g[MAXN][MAXN];

vector <int> E[MAXN];
void dfs (int u){
	vis[u] = 1;
	for (Int v = 1;v <= n;++ v)
		if (!vis[v] && g[u][v])
			E[u].push_back (v),deg[v] ++,dfs (v);
}

int a[MAXN];
void topo (){
	priority_queue <int> q;int cnt = 0;
	for (Int i = 1;i <= n;++ i) vis[i] = 0;
	for (Int i = 1;i <= n;++ i) if (!deg[i]) q.push (i);
	while (!q.empty()){
		int u = q.top();q.pop (),a[++ cnt] = s[u];
		for (Int v : E[u]) if (!-- deg[v]) q.push (v);
	}
}

signed main(){
	read (n);
	for (Int i = 1;i <= n;++ i) read (s[i]);
	sort (s + 1,s + n + 1);
	for (Int i = 1;i <= n;++ i)
		for (Int j = i + 1;j <= n;++ j)
			if (__gcd (s[i],s[j]) > 1) g[i][j] = g[j][i] = 1;
	for (Int i = 1;i <= n;++ i) if (!vis[i]) dfs (i);
	topo ();
	for (Int i = 1;i <= n;++ i) write (a[i]),putchar (' ');putchar ('\n');
	return 0;
}
posted @ 2022-02-13 19:53  Dark_Romance  阅读(63)  评论(2编辑  收藏  举报