1. 程式人生 > >【codeforces 691 D】【並查集 或者 dfs】aps in Permutation【給一個1到N的排列,M個操作,每次可以交換X Y位置上的數字,求可以得到的最大字典序的數列】

【codeforces 691 D】【並查集 或者 dfs】aps in Permutation【給一個1到N的排列,M個操作,每次可以交換X Y位置上的數字,求可以得到的最大字典序的數列】

題意: 給一個1到N的排列,M個操作(1<=N,M<=106),每個操作可以交換X Y位置上的數字,求可以得到的最大字典序的數列。

思路:

把位置分成若干塊,每一塊裡面的位置都是可以被這一塊裡另一個位置經過若干次調換的(類似強連通,位置可達),因而可以用並查集維護。
然後把每一塊位置裡的 位置按從小到大排序,位置上的值按從大到小排序,依次填入位置(最大的放最前)。
每個點都會被放且僅放一次。

當然這題也可以dfs

程式碼:

#include <bits/stdc++.h>
using  namespace  std;
#define pb push_back

const int inf=0x3f3f3f3f;
const int N=1e6+10; 

std::vector<int> pos[N];
std::vector<int> val[N];
int p[N], a[N], ans[N];

int Find(int x){
  return p[x]==x?x:p[x]=Find(p[x]);
}

void unite(int x,int y){
  x=Find(x);
  y=Find(y);
  if(x!=y)
        p[y]=x;
}

int  main(){
    int n, m;
    scanf("%d%d", &n, &m);
    for(int i=1; i<=n; i++){
        scanf("%d", &a[i]);
        p[i]=i;   
    }
    while(m--){
        int u, v;
        scanf("%d%d", &u, &v); 
        unite(u, v);
    }
    for(int i=1; i<=n; i++){
        int x=Find(i);
        pos[x].pb(i);
        val[x].pb(a[i]);
    }
    for(int i=1; i<=n; i++){
        sort(val[i].begin(), val[i].end(), greater<int>());
        for(int j=0; j<pos[i].size(); j++){
            ans[pos[i][j]] = val[i][j];
        }
    }
    for(int i=1; i<=n; i++)printf("%d%c", ans[i], i==n ? '\n':' ');
    return 0;
}

D. Swaps in Permutation time limit per test 5 seconds memory limit per test 256 megabytes input standard input output standard output

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 number1 ≤ i ≤ n exists, so pk = 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 a positions, 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