题解 | #染色#
染色
https://www.nowcoder.com/practice/cc3200f72c06432eb0b073c0ca981f63
#include <bits/stdc++.h> // 模拟一定超时,并查集思想! using namespace std; int main() { int n, q, x, y; cin >> n; vector<int> a(n + 1); unordered_map<int,list<int>> cnt; for (int i = 1; i <= n; i++) { cin >> a[i]; cnt[a[i]].push_back(i); } cin >> q; while (q--) { cin >> x >> y; if(x == y) continue; // 归并! cnt[y].splice(cnt[y].end(),cnt[x]); } for(auto[x,idx] : cnt){ for(auto i : idx) a[i] = x; } for(int i = 1; i <= n; i++) cout << a[i] << " "; return 0; }