Swaps in Permutation
You are given a permutation of the numbers 1, 2, ..., n and m pairs of positions (aj, bj).
At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get?
Let p and q be two permutations of the numbers 1, 2, ..., n. p is lexicographically smaller than the q if a number 1 ≤ i ≤ n exists, sopk = qk for 1 ≤ k < i and pi < qi.
The first line contains two integers n and m (1 ≤ n, m ≤ 106) — the length of the permutation p and the number of pairs of positions.
The second line contains n distinct integers pi (1 ≤ pi ≤ n) — the elements of the permutation p.
Each of the last m lines contains two integers (aj, bj) (1 ≤ aj, bj ≤ n) — the pairs of positions to swap. Note that you are given apositions, not the values to swap.
Print the only line with n distinct integers p'i (1 ≤ p'i ≤ n) — the lexicographically maximal permutation one can get.
9 6
1 2 3 4 5 6 7 8 9
1 4
4 7
2 5
5 8
3 6
6 9
7 8 9 4 5 6 1 2 3
分析:一个联通体内的数从大到小排列就好;
代码:
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <algorithm> #include <climits> #include <cstring> #include <string> #include <set> #include <map> #include <queue> #include <stack> #include <vector> #include <list> #include <ext/rope> #define rep(i,m,n) for(i=m;i<=n;i++) #define rsp(it,s) for(set<int>::iterator it=s.begin();it!=s.end();it++) #define vi vector<int> #define pii pair<int,int> #define inf 0x3f3f3f3f #define pb push_back #define mp make_pair #define fi first #define se second #define ll long long #define pi acos(-1.0) const int maxn=1e6+10; const int mod=1e6+3; const int dis[4][2]={{0,1},{-1,0},{0,-1},{1,0}}; using namespace std; using namespace __gnu_cxx; ll gcd(ll p,ll q){return q==0?p:gcd(q,p%q);} ll qpow(ll p,ll q){ll f=1;while(q){if(q&1)f=f*p%mod;p=p*p%mod;q>>=1;}return f;} int n,m,a[maxn],vis[maxn]; vi b[maxn],c; set<int>p,q; void dfs(int now) { vis[now]=1;q.insert(now);c.pb(a[now]); for(int x:b[now])if(!vis[x])dfs(x); } int main() { int i,j,k,t; scanf("%d%d",&n,&m); rep(i,1,n)scanf("%d",&a[i]); while(m--) { scanf("%d%d",&j,&k);b[j].pb(k),b[k].pb(j); p.insert(j),p.insert(k); } for(int x:p) { if(!vis[x]) { q.clear();c.clear(); dfs(x); sort(c.rbegin(),c.rend());j=0; for(int y:q)a[y]=c[j++]; } } rep(i,1,n)printf("%d ",a[i]); //system ("pause"); return 0; }