Swaps in Permutation

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, ..., np is lexicographically smaller than the q if a number 1 ≤ i ≤ n exists, sopk = qk for 1 ≤ k < i and pi < qi.

Input

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.

Output

Print the only line with n distinct integers p'i (1 ≤ p'i ≤ n) — the lexicographically maximal permutation one can get.

Example
input
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
分析:一个联通体内的数从大到小排列就好;
代码:
#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+;
const int mod=1e6+;
const int dis[][]={{,},{-,},{,-},{,}};
using namespace std;
using namespace __gnu_cxx;
ll gcd(ll p,ll q){return q==?p:gcd(q,p%q);}
ll qpow(ll p,ll q){ll f=;while(q){if(q&)f=f*p%mod;p=p*p%mod;q>>=;}return f;}
int n,m,a[maxn],vis[maxn];
vi b[maxn],c;
set<int>p,q;
void dfs(int now)
{
vis[now]=;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,,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=;
for(int y:q)a[y]=c[j++];
}
}
rep(i,,n)printf("%d ",a[i]);
//system ("pause");
return ;
}
上一篇:线程概念( 线程的特点,进程与线程的关系, 线程和python理论知识,线程的创建)


下一篇:POJ_3662_Telephone_Lines_(二分+最短路)