CodeForces 691D:Swaps in Permutation(并查集)

http://codeforces.com/contest/691/problem/D

D. 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, so pk = qkfor 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

题意:给出一个含n个元素的序列,再给出m个可以无限次互相交换位置的下标,求出交换以后让整个序列的字典序最大。
思路:用并查集分出可以交换位置的下标集合,然后用vector装每个集合的下标和元素,然后每次查找集合的根节点的时候对每个集合的元素排序一下就好了。
 #include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
#define N 1000005
vector <int> num[N];
vector <int> pos[N];
int p[N],a[N],ans[N];
int fa[N]; int Find(int x)
{
if(x==fa[x]) return x;
return fa[x]=Find(fa[x]);
} void Merge(int x,int y)
{
x=Find(x),y=Find(y);
if(x==y) return ;
fa[x]=y;
} int main()
{
int n,m;
cin>>n>>m;
for(int i=;i<=n;i++){
fa[i]=i;
scanf("%d",&a[i]);
p[i]=i;
}
for(int i=;i<=m;i++){
int a,b;
scanf("%d%d",&a,&b);
Merge(a,b);
}
for(int i=;i<=n;i++){
int x=Find(i);
pos[x].push_back(i);
num[x].push_back(-a[i]);
//因为要从大到小排序,而默认的排序是从小到大,所以先取负后面再取正
}
for(int i=;i<=n;i++){
sort(num[i].begin(),num[i].end());
for(int j=;j<pos[i].size();j++){
ans[pos[i][j]]=-num[i][j];
}
}
for(int i=;i<=n;i++){
printf("%d ",ans[i]);
}
return ;
}
上一篇:POJ_3662_Telephone_Lines_(二分+最短路)


下一篇:[Python 2.7] Hello World CGI HTTP Server