题目链接:
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.
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.
Print 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 9
7 8 9 4 5 6 1 2 3
题意:
给一个数列,现在可以交换ai和bi,问能得到的最大的字典序的数列是什么;
思路:
把能交换位置的数放在同一个集合里;可以dfs找到,然后把这些数和位置排序对应就好了;不知道cf的数据怎么了;
AC代码:
#include <bits/stdc++.h> #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> using namespace std; #define For(i,j,n) for(int i=j;i<=n;i++) #define mst(ss,b) memset(ss,b,sizeof(ss)); typedef long long LL; template<class T> void read(T&num) { char CH; bool F=false; for(CH=getchar();CH<'0'||CH>'9';F= CH=='-',CH=getchar()); for(num=0;CH>='0'&&CH<='9';num=num*10+CH-'0',CH=getchar()); F && (num=-num); } int stk[70], tp; template<class T> inline void print(T p) { if(!p) { puts("0"); return; } while(p) stk[++ tp] = p%10, p/=10; while(tp) putchar(stk[tp--] + '0'); putchar(' '); } const LL mod=1e9+7; const double PI=acos(-1.0); const LL inf=1e18; const int N=1e6+10; const int maxn=1005; const double eps=1e-10; int n,m,p[N],a[N],b[N],ans[N],cnt,vis[N]; vector<int>ve[N]; void dfs(int x) { vis[x]=1; a[++cnt]=p[x]; b[cnt]=x; int len =ve[x].size(); For(i,0,len-1) { int y =ve[x][i]; if(!vis[y]) dfs(y); } } int cmp(int x,int y) { return x>y; } void solve() { sort(a+1,a+cnt+1,cmp); sort(b+1,b+cnt+1); For(i,1,cnt)ans[b[i]]=a[i]; } int main() { read(n);read(m); For(i,1,n)read(p[i]); int u,v; For(i,1,m) { read(u);read(v); ve[u].push_back(v); ve[v].push_back(u); } For(i,1,n) { if(!vis[i]) { cnt=0; dfs(i); solve(); } } For(i,1,n)printf("%d ",ans[i]); return 0; }