Swaps in permutation
You are given a permutation of the numbers 1, 2, ..., n and m pairs of positions (a J, bJ).
At each step you can choose a pair from the given positions and swap the numbers on that positions. What is the lexicographically maximal permutation one can get?
Let P and Q is the permutations of the numbers 1, 2, ..., n. P is lexicographically smaller than the Q If a number 1≤ i ≤ n exist s, sop-k = qk for 1≤ K < i and c23>Pi < qI.
Input
The first line contains integers n and m (1≤ n, m ≤106)-the le Ngth of the permutation p and the number of pairs of positions.
The second line contains n distinct integers pi (1≤ p c18>i ≤ n)-the elements of the permutation p.
Each of the last m lines contains and integers (aJ, bJ) ( 1≤ a J, bj ≤ n)-the pairs of positions to swap. Notethat is given a positions, not the values to swap.
Output
Print the only line with n distinct integers p'i (1≤ P' c26>i ≤ n)-the lexicographically maximal permutation one can get.
Exampleinput
9 6
1 2 3 4 5 6 7 8 9
1 4
4 7
2 5
5 8
3 6
6 9
Output
7 8 9 4 5 6 1 2 3
Analysis: A unicom in the body of the number from large to small arrangement is good;
Code:
#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>#defineRep (I,m,n) for (i=m;i<=n;i++)#defineRSP (It,s) for (Set<int>::iterator It=s.begin (); It!=s.end (); it++)#defineVI vector<int>#definePII pair<int,int>#defineINF 0x3f3f3f3f#definePB Push_back#defineMP Make_pair#defineFi first#defineSe Second#definell Long Long#definePi ACOs (-1.0)Const intmaxn=1e6+Ten;Const intmod=1e6+3;Const intdis[4][2]={{0,1},{-1,0},{0,-1},{1,0}};using namespacestd;using namespace__gnu_cxx;ll gcd (ll p,ll q) {returnq==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;}returnF;}intN,m,a[maxn],vis[maxn];vi b[maxn],c;Set<int>p,q;voidDfsintNow ) {Vis[now]=1; Q.insert (now); C.PB (A[now]); for(intX:b[now])if(!vis[x]) DFS (x);}intMain () {inti,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(intx:p) {if(!Vis[x]) {q.clear (); C.clear (); DFS (x); Sort (C.rbegin (), C.rend ()); J=0; for(intY:Q) a[y]=c[j++]; }} rep (I,1, N) printf ("%d", A[i]); //System ("pause"); return 0;}
Swaps in permutation