classUF { public: vector<int> f; vector<int> size; int n; UF(int _n): n(_n), f(_n), size(_n, 1) { iota(f.begin(), f.end(), 0); } intfind(int x){ return f[x] == x ? x : f[x] = find(f[x]); } void _union(int x, int y) { x = find(x); y = find(y); if (x != y) { if (size[x] < size[y]) swap(x, y); f[y] = x; size[x] += size[y]; } } }; classSolution { public: intminSwapsCouples(vector<int>& row){ constint n = row.size(); int tot = n / 2; UF uf(tot); for (int i = 0; i < n; i += 2) uf._union(row[i] / 2, row[i + 1] / 2); unordered_map<int, int> m; for (int i = 0; i < tot; ++i) ++m[uf.find(i)]; int ans = 0; // for each connected set with "sz" as size, // "sz - 1" would be the number of needed swaps. for (constauto& [_, sz] : m) ans += sz - 1; return ans; } };
classSolution { public: intminSwapsCouples(vector<int>& row){ constint n = row.size(); int tot = n / 2; vector<vector<int>> graph(tot); for (int i = 0; i < n; i += 2) { int l = row[i] / 2; int r = row[i + 1] / 2; graph[l].emplace_back(r); graph[r].emplace_back(l); } vector<bool> visited(tot, false); int ans = 0; for (int i = 0; i < tot; ++i) if (!visited[i]) { queue<int> q; q.push(i); visited[i] = true; int cnt = 0; while (!q.empty()) { int x = q.front(); q.pop(); ++cnt; for (int nx : graph[x]) if (!visited[nx]) { q.push(nx); visited[nx] = true; } } ans += cnt - 1; } return ans; } };