赞
踩
class UnionFind { public: int count; vector<int> parent, size; UnionFind(int n) { count = n; parent.resize(n); size.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } void unite(int a, int b) { int rootA = find_root(a); int rootB = find_root(b); if (rootA == rootB) return; if (size[rootA] < size[rootB]) { parent[rootA] = rootB; size[rootB] += size[rootA]; } else { parent[rootB] = parent[rootA]; size[rootA] += size[rootB]; } count--; } bool connected(int a, int b) { int rootA = find_root(a); int rootB = find_root(b); return rootA == rootB; } int find_root(int node) { while (parent[node] != node) { parent[node] = parent[parent[node]]; node = parent[node]; } return node; } }; class Solution { public: int makeConnected(int n, vector<vector<int>>& connections) { int num_edge = connections.size(); if (num_edge < n - 1) return -1; UnionFind uf(n); for (int i = 0; i < num_edge; i++) uf.unite(connections[i][0], connections[i][1]); // 连通分量需要的最少边数 = 连通分量 - 1 return uf.count - 1; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。