[AGC010E] Rearranging
Description
https://www.luogu.com.cn/problem/AT_agc010_e
Solution
后手交换相邻的互质的数,也就是说如果序列已经确定,那么两个不互质的数的相对顺序不改变。
假设序列已经确定,那么把 $i<j,(a_i,a_j)\not = 1$ 的点对 $(i,j)$ 连边,连出来一定是个 DAG。把拓扑排序的队列换成优先队列就是后手最优。
考虑先手的最优策略,先将数组排序。然后将两个互质的数之间连无向边。先手需要定向。对于每个连通块内部。考虑贪心的将最小的点向外连边,依次递归。
先手的最优策略已经被我们连边,现在只需要模拟后手的最优策略即可。
如果不满足性质就不改变相对顺序,算不算一个小 trick?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| #include<bits/stdc++.h> #define ll long long #define ull unsigned long long #define maxn 2005 #define put() putchar('\n') #define Tp template<typename Ty> #define Ts template<typename Ty,typename... Ar> using namespace std; void read(int &x){ int f=1;x=0;char c=getchar(); while (c<'0'||c>'9') {if (c=='-') f=-1;c=getchar();} while (c>='0'&&c<='9') {x=x*10+c-'0';c=getchar();} x*=f; } namespace Debug{ Tp void _debug(char* f,Ty t){cerr<<f<<'='<<t<<endl;} Ts void _debug(char* f,Ty x,Ar... y){while(*f!=',') cerr<<*f++;cerr<<'='<<x<<",";_debug(f+1,y...);} Tp ostream& operator<<(ostream& os,vector<Ty>& V){os<<"[";for(auto& vv:V) os<<vv<<",";os<<"]";return os;} #define gdb(...) _debug((char*)#__VA_ARGS__,__VA_ARGS__) }using namespace Debug; #define fi first #define se second #define mk make_pair const int mod=1e9+7; int power(int x,int y=mod-2) { int sum=1; while (y) { if (y&1) sum=sum*x%mod; x=x*x%mod;y>>=1; } return sum; } priority_queue<int>q; int n,a[maxn],c[maxn][maxn]; int vis[maxn],in[maxn],tot,Ans[maxn]; vector<int>to[maxn]; void dfs(int x) { vis[x]=1; for (int i=1;i<=n;i++) if (!vis[i]&&c[x][i]) { to[x].push_back(i);in[i]++; dfs(i); } } signed main(void){ int i,j,x; read(n); for (i=1;i<=n;i++) read(a[i]); sort(a+1,a+1+n); for (i=1;i<=n;i++) { for (j=1;j<=n;j++) c[i][j]=(__gcd(a[i],a[j])!=1); } for (i=1;i<=n;i++) if (!vis[i]) dfs(i); for (i=1;i<=n;i++) if (!in[i]) q.push(i); while (!q.empty()) { x=q.top();q.pop(); Ans[++tot]=x; for (auto y:to[x]) if (!--in[y]) { q.push(y); } } for (i=1;i<=n;i++) printf("%d ",a[Ans[i]]); return 0; }
|