1319. 连通网络的操作次数(并查集)
1319. 连通网络的操作次数
用以太网线缆将 n
台计算机连接成一个网络,计算机的编号从 0
到 n-1
。线缆用 connections
表示,其中 connections[i] = [a, b]
连接了计算机 a
和 b
。
网络中的任何一台计算机都可以通过网络直接或者间接访问同一个网络中其他任意一台计算机。
给你这个计算机网络的初始布线 connections
,你可以拔开任意两台直连计算机之间的线缆,并用它连接一对未直连的计算机。请你计算并返回使所有计算机都连通所需的最少操作次数。如果不可能,则返回 -1 。
示例 1:
输入:n = 4, connections = [[0,1],[0,2],[1,2]] 输出:1 解释:拔下计算机 1 和 2 之间的线缆,并将它插到计算机 1 和 3 上。
示例 2:
输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]] 输出:2
示例 3:
输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2]] 输出:-1 解释:线缆数量不足。
示例 4:
输入:n = 5, connections = [[0,1],[0,2],[3,4],[2,3]] 输出:0
提示:
1 <= n <= 10^5
1 <= connections.length <= min(n*(n-1)/2, 10^5)
connections[i].length == 2
0 <= connections[i][0], connections[i][1] < n
connections[i][0] != connections[i][1]
- 没有重复的连接。
- 两台计算机不会通过多条线缆连接。
1 class Solution { 2 public: 3 vector<int> parent; 4 int numOfGroup; // 连通网络分组数 5 void initUnionFind(int n) { 6 parent.resize(n); 7 numOfGroup = n; // 初始化每个电脑互不连通,分组数即为电脑数 8 for (int i = 0; i < n; i++) { 9 parent[i] = i; 10 } 11 } 12 int findRoot(int x) { 13 int root = x; 14 while (root != parent[root]) { 15 root = parent[root]; 16 } 17 while (x != root) { 18 int next = parent[x]; 19 parent[x] = root; 20 x = next; 21 } 22 return root; 23 } 24 bool isConnected(int x, int y) { 25 return (findRoot(x) == findRoot(y)); 26 } 27 void unify(int x, int y) { 28 if (isConnected(x, y)) { 29 return; 30 } 31 int xRoot = findRoot(x); 32 int yRoot = findRoot(y); 33 if (xRoot < yRoot) { 34 parent[xRoot] = yRoot; 35 } else { 36 parent[yRoot] = xRoot; 37 } 38 numOfGroup--; 39 return; 40 } 41 int makeConnected(int n, vector<vector<int>>& connections) { 42 // 初始化并查集 43 initUnionFind(n); 44 vector<std::pair<int, int>> circle; // 形成环的网线连接的两点集合 45 for (auto &vec : connections) { 46 if (isConnected(vec[0], vec[1])) { 47 circle.push_back(make_pair(vec[0], vec[1])); 48 } else { 49 unify(vec[0], vec[1]); 50 } 51 } 52 int numOfRedundantConnections = circle.size(); 53 if (numOfGroup == 1) { 54 return 0; 55 } 56 if ((numOfGroup - 1) > numOfRedundantConnections) { 57 return -1; 58 } 59 return (numOfGroup - 1); 60 } 61 };