classSolution { intgetParent(vector<int>& gr, int a){ return gr[a] == a ? a : gr[a] = getParent(gr, gr[a]); } voidmerge(vector<int>& gr, int a, int b){ int pa = getParent(gr,a); int pb = getParent(gr,b); gr[pa] = gr[pb] = min(pa,pb); } public: string smallestStringWithSwaps(string s, vector<vector<int>>& pairs){ int n = s.length(); vector<int> gr(n); for(int i = 0; i < n; i++) gr[i] = i; for(auto& p : pairs) { merge(gr,p[0],p[1]); }
unordered_map<int, vector<char>> m; for(int i = 0; i < n; i++) { m[getParent(gr, i)].push_back(s[i]); } for(auto& [k, v]: m) { sort(v.begin(), v.end(), greater<char>()); }
for(int i = 0; i < n; i++) { s[i] = m[gr[i]].back(); m[gr[i]].pop_back(); }