Leetcode-5199 Smallest String With Swaps(交换字符串中的元素)
1 #define _for(i,a,b) for(int i = (a);i < b;i ++) 2 #define _rep(i,a,b) for(int i = (a);i > b;i --) 3 #define INF 0x3f3f3f3f 4 #define MOD 1000000007 5 #define pb push_back 6 #define maxn 100003 7 8 int par[maxn]; //父亲 9 int high[maxn]; //树的高度 10 11 void init(int n) 12 { 13 _for(i,0,n) 14 { 15 par[i] = i; 16 high[i] = 0; 17 } 18 } 19 20 int find(int x) 21 { 22 return par[x] == x ? x : par[x] = find(par[x]); 23 } 24 25 void unite(int x,int y) 26 { 27 x = find(x); 28 y = find(y); 29 if(x==y) return ; 30 31 if(high[x]<high[y]) 32 par[x] = y; 33 else 34 { 35 par[y] = x; 36 if(high[x]==high[y]) 37 high[x] ++; 38 } 39 } 40 41 bool same(int x,int y) 42 { 43 return find(x) == find(y); 44 } 45 46 class Solution 47 { 48 vector<int> a[maxn]; 49 public: 50 string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) 51 { 52 int n = s.size(); 53 string rnt = s; 54 init(n); 55 _for(i,0,pairs.size()) 56 unite(pairs[i][0],pairs[i][1]); 57 58 _for(i,0,s.size()) 59 a[find(i)].pb(i); 60 61 _for(i,0,n) 62 { 63 string tmp; 64 _for(j,0,a[i].size()) 65 tmp += s[a[i][j]]; 66 sort(tmp.begin(),tmp.end()); 67 _for(j,0,a[i].size()) 68 rnt[a[i][j]] = tmp[j]; 69 } 70 return rnt; 71 } 72 };