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
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
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 a positions, not the values to swap.
OutputPrint 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 9Output
7 8 9 4 5 6 1 2 3
說給你一個排列,然後給你M對關係,記錄著排列中的陣列下標,你可以利用這M對關係中的任意對無數次,對陣列下標進行交換,然後找到字典序最大的排列。
思路:關係嘛,自然而然想到通過並查集構建若干個連通塊(因為不在一個連通塊裡說明木有關係,也就不能進行交換),接著建立好關於陣列下標的連通塊後,對於每個連通塊,我們自然而然的想到應該從大往小輸出,於是我們可以利用強大的STL:優先佇列。對每一個連通塊的根節點建一個優先佇列,然後用來存連通塊中對應陣列下標的陣列的值(自動從大到小排序還是非常茲瓷的),然後遍歷每個優先佇列中的所有元素就好了。
槽點:寫Find函式竟然思博的直接寫if ... else return Find(pre[x])瞭然後一直RE(並查集不是當年窩最拿手的幾個思博程式碼之一麼= =|||)。。。看有5S中1E6的資料不慫直接C++輸入輸出,還是T了,喜聞樂見。注意優先佇列的清空。
程式碼:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=1000005;
priority_queue<int> ans[maxn];
int pre[maxn];
int n,m;
int a[maxn];
int Find(int x)
{
if(x==pre[x])
return pre[x];
return pre[x]=Find(pre[x]);//習習蛤蛤
}
void join(int x,int y)
{
int fx=Find(x);
int fy=Find(y);
if(fx!=fy)
{
pre[fx]=fy;
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
pre[i]=i;
}
while(m--)
{
int a,b;
scanf("%d%d",&a,&b);
join(a,b);
}
for(int i=1;i<=n;i++)
{
ans[pre[Find(i)]].push(a[i]);//看該陣列下標所對應權值在以哪個節點為根的連通塊中,存入,自動排序OK。
}
for(int i=1;i<=n;i++)
{
printf("%d ",ans[pre[i]].top());
ans[pre[i]].pop();//輸出後記得拿出來= =
}
return 0;
}