The number of operations of the network communication LeetCode 1319.

1319. The number of operations of the communication network

Ethernet cable  n is connected to a computer network, computers are numbered from  0 to  n-1. Cable-  connections expressed, which  connections[i] = [a, b] is connected to the computer  a and  b.

The network any computer can access the same network indirectly other directly or through any computer network.

Give you the initial wiring computer network  connections, you can unplug any two straight cable between the computer and use it to connect a pair of computers are not directly connected. Please calculate and return all computers are communicating the minimum number of operations required. If this is not -1. 

 

Example 1:

Input: n-=. 4, Connections = [[0,1], [0,2], [1,2]]
 Output: 1
 Explanation: unplug the cable between the computer 1 and 2, and plug it into the computer and the upper 13.

Example 2:

Input: n-=. 6, Connections = [[0,1], [0,2], [0,3], [1,2], [l, 3]]
 Output: 2

Example 3:

Input: n-=. 6, Connections = [[0,1], [0,2], [0,3], [1,2]]
 Output: -1
 Explanation: insufficient number of cables.

Example 4:

Input: n-=. 5, Connections = [[0,1], [0,2], [3,4-], [2,3]]
 Output: 0

Thinking : dfs can be set or checked to determine the number and the communication block, here disjoint-set, the number of operations required is the number of connected block minus one

class Solution {
public:
    int father[100001];
    int findfather(int x){
        int a = x;
        while(x!=father[x]){
            x = father[x];
        }
        while(a!=father[a]){
            int z = a;
            a = father[a];
            father[z] = x;
        }
        return x;
    }
    int makeConnected(int n, vector<vector<int>>& connections) {
        int num = connections.size();
        for(int i = 0;i<n;i++){
            father[i] = i;
        }
        int a,b,faA,faB;
        for(int i = 0;i<connections.size();i++){
            a = connections[i][0];
            b = connections[i][1];
            faA = findfather(a);
            faB = findfather(b);
            if(faA!=faB)father[faA] = faB;
        }
        int isroot[n] = {0},sum = 0;
        //查找有多少个连通块
        for(int i = 0;i<n;i++){
            isroot[findfather(i)]++;
        }
        for(int i = 0;i<n;i++){
            if(isroot[i]!=0)sum++;
        }
        //如果线缆足够则输出操作次数,否则输出-1
        if(num>=n-1)return sum-1;
        else return -1;
    }
};

 

Published 35 original articles · won praise 3 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_40167974/article/details/104675170