鱼C论坛

 找回密码
 立即注册
查看: 1928|回复: 0

[技术交流] C++刷leetcode(1319. 连通网络的操作次数)【并查集】

[复制链接]
发表于 2020-5-31 14:49:27 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目描述:
  1. 用以太网线缆将 n 台计算机连接成一个网络,计算机的编号从 0 到 n-1。线缆用 connections 表示,其中 connections[i] = [a, b] 连接了计算机 a 和 b。

  2. 网络中的任何一台计算机都可以通过网络直接或者间接访问同一个网络中其他任意一台计算机。

  3. 给你这个计算机网络的初始布线 connections,你可以拔开任意两台直连计算机之间的线缆,并用它连接一对未直连的计算机。请你计算并返回使所有计算机都连通所需的最少操作次数。如果不可能,则返回 -1 。 

  4.  

  5. 示例 1:



  6. 输入:n = 4, connections = [[0,1],[0,2],[1,2]]
  7. 输出:1
  8. 解释:拔下计算机 1 和 2 之间的线缆,并将它插到计算机 1 和 3 上。
  9. 示例 2:



  10. 输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
  11. 输出:2
  12. 示例 3:

  13. 输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
  14. 输出:-1
  15. 解释:线缆数量不足。
  16. 示例 4:

  17. 输入:n = 5, connections = [[0,1],[0,2],[3,4],[2,3]]
  18. 输出:0
  19.  

  20. 提示:

  21. 1 <= n <= 10^5
  22. 1 <= connections.length <= min(n*(n-1)/2, 10^5)
  23. connections[i].length == 2
  24. 0 <= connections[i][0], connections[i][1]&#160;< n
  25. connections[i][0] != connections[i][1]
  26. 没有重复的连接。
  27. 两台计算机不会通过多条线缆连接。

  28. 来源:力扣(LeetCode)
  29. 链接:https://leetcode-cn.com/problems/number-of-operations-to-make-network-connected
  30. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码


  1. class Solution {
  2. public:
  3.     int find_root(int x, vector<int>& father){
  4.         if(father[x] != x) return find_root(father[x], father);
  5.         return x;
  6.     }
  7.     void unite(int x, int y, vector<int>& father){
  8.         int temp1 = find_root(x, father);
  9.         int temp2 = find_root(y, father);
  10.         if(temp1 != temp2){
  11.             father[temp1] = temp2;
  12.         }
  13.     }
  14.     int makeConnected(int n, vector<vector<int>>& connections) {
  15.         if(connections.size() < n-1) return -1;
  16.         vector<int> father(n, 0);
  17.         //初始化father
  18.         for(int i = 0; i < n; i++){
  19.             father[i] = i;
  20.         }
  21.         //根据connections构建并查集
  22.         int len = connections.size();
  23.         for(auto cha : connections){
  24.             unite(cha[0], cha[1], father);
  25.         }
  26.         //确定一共有几个group
  27.         set<int> temp;
  28.         for(int i = 0; i < n; i++){
  29.             temp.insert(find_root(i, father));
  30.         }
  31.         int group = temp.size();
  32.         return group - 1;
  33.     }
  34. };
复制代码

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-5 03:07

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表