zoukankan      html  css  js  c++  java
  • 1319. 连通网络的操作次数 并查集

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

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

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

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

    什么时候返回-1?
    当边数小于点数的时候,必返回-1
    否则,返回图中连通分量的数目-1即可

    class Solution {
    public:
        unordered_map <int, int> fa;
        unordered_map <int, int> rank;
        int cnt;
    
        int find(int x) {
            if (!fa.count(x)) {
                fa[x] = x;
                rank[x] = 1;
            }
            return fa[x] == x ? fa[x] : fa[x] = find(fa[x]);
        }
    
        bool same(int x, int y) {
            return find(x) == find(y);
        }
    
        void merge(int x, int y) {
            int xx = find(x);
            int yy = find(y);
            if (same(xx, yy)) {
                return;
            }
            if (rank[xx] < rank[yy]) {
                swap(xx, yy);
            }
            cnt--;
            rank[xx] += rank[yy];
            fa[yy] = xx;
        }
    
        int makeConnected(int n, vector<vector<int>>& connections) {
            cnt = n;
    
            if (connections.size() < n - 1) {
                return  -1;
            }
    
            for (int i = 0; i < connections.size(); i++) {
                int u = connections[i][0];
                int v = connections[i][1];
                merge(u, v);
            }
    
            return cnt - 1;
        }
    };
    
  • 相关阅读:
    HashMap的C++实现
    MyString的简单实现
    C++智能指针实现
    static_cast 、const_cast、dynamic_cast、reinterpret_cast 关键字简单解释
    对数组取地址
    修改const变量
    红黑树简单总结
    MyInt的简单实现
    全排列之递归与非递归算法实现总结
    不用辅助空间的归并排序
  • 原文地址:https://www.cnblogs.com/xgbt/p/14323033.html
Copyright © 2011-2022 走看看