Description
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.
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.
Sample Input
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
题意:给你一个序列,然后给你一些可以进行交换的位置信息,这些交换信息可以无限进行,而且没有顺序限制(比如说1 4,即1号和四号位置中的数值可以进行交换,并且这种交换行为可以随时进行,没有顺序影响,4 7交换完了,1 4 依旧可以进行交换)。
通过题目分析,我们可以知道,只要序列中的两个位置有直接或者间接的关系,那么这几个位置可以任意交换,没有任何阻碍。
如此,我们要求的让这个序列最大的情况就相对容易了。
先将有关系的位置(即可以进行交换)建立成一个链表,然后对这个链表排序,将数值大的放在位置小的地方即可
详细方法请看代码的解释
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int MAXN = 1e6 + 5;
int n, m, x, y;
int A[MAXN];//表示序列
int par[MAXN], chi[MAXN];//表示父亲的数组和记录儿子的数组
int O[MAXN], OI[MAXN];//O数组保存用于针对某一条链表对应节点的数字,OI保存某一条链表中对应节点在A序列中的编号
bool vis[MAXN];//当前节点是否已经进行了优化处理
void init() {//初始化链表数据,双向链表
memset(vis, false, sizeof(vis));
for(int i = 0; i < MAXN; i ++) par[i] = chi[i] = i;
}
int findp(int x) {//find_par的缩写,获取链表的顶级父节点,即链表的头节点
return par[x] == x ? x : findp(par[x]);
}
int findc(int x) {//find_child的缩写,获取链表的最底层儿子,即链表的尾节点
return chi[x] == x ? x : findc(chi[x]);
}
void unite(int x, int y) {//连接两个需要联系的链表,方法:得到一个链表的头,另一个链表的尾,然后将头连接到尾部即可
int nx = findp(x);//获取x节点所在的链表的头节点
int ny = findp(y);//获取y节点所在的链表的头节点
if(nx == ny) return;//如果两两链表头节点相同,证明他们是同一个链表,所以返回
int cy = findc(y);//得到y节点坐在的链表的尾节点
par[nx] = cy;//进行连接操作
chi[cy] = nx;
}
void sortl(int x) {//对一条链表中的数据进行排序处理
int cnt = 0;
x = findp(x);//得到x节点所在链表的头节点
if(vis[x]) return;
while(chi[x] != x) {
vis[x] = true;//记录已经访问
OI[cnt] = x;//得到这条链表节点在A序列中的编号
O[cnt ++] = A[x];//得到这条链表中节点在A序列中的数值
x = chi[x];
}
vis[x] = true;
OI[cnt] = x;
O[cnt ++] = A[x];
sort(OI, OI + cnt);//编号升序,将位置小的放在数组最前方
sort(O, O + cnt, greater<int>() );//数值降序,将数值最大的放在数组最前方
for(int i = 0; i < cnt; i ++){//将大的数值放在位置小的地方
A[OI[i]] = O[i];
}
}
int main() {
while(~scanf("%d%d", &n, &m)) {
init();
for(int i = 1; i <= n; i ++) {
scanf("%d", &A[i]);
}
for(int i = 1; i <= m; i ++) {
scanf("%d%d", &x, &y);
unite(x, y);//加入链表
}
for(int i = 1; i <= n; i ++) {
sortl(i);//sort_line缩写,对每一个链表中的数据进行排序
}
for(int i = 1; i <= n; i ++) {
printf("%d%c", A[i], i == n ? '\n':' ');
}
}
return 0;
}