1/23 Likou Daily One Question~The number of operations of Unicom Network

As the title~

Use Ethernet cables to connect n computers into a network, and the computer numbers are from 0 to n-1. Cables are represented by connections, where connections[i] = [a, b] connect computers a and b.
Any computer in the network can directly or indirectly access any other computer in the same network through the network.
To give you the initial wiring connections of this computer network, you can unplug the cable between any two directly connected computers and use it to connect a pair of computers that are not directly connected. Please calculate and return the minimum number of operations required to connect all computers. If it is not possible, -1 is returned.

Example 1:
Insert picture description here
Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
Explanation: Unplug the cable between computers 1 and 2, and connect it Plug into computers 1 and 3.

Example 2: Insert picture description here
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
Output: 2

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

Tips:
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]
There are no duplicate connections.
Two computers will not be connected by multiple cables.

code show as below:

int find(int *parent, int x) {
    
    
    if (parent[x] != x) {
    
    
        parent[x] = find(parent, parent[x]);
    }
    return parent[x];
}//寻找父节点
int makeConnected(int n, int** connections, int connectionsSize, int* connectionsColSize){
    
    
    int count = n;
    int *parent = (int *)malloc(n * sizeof(int));//给他分配空间
    if (connectionsSize < n - 1) {
    
    
        return -1;
    }//如果需要连接n个点,至少需要n-1条线,否则,直接错误
    for (int i = 0; i < n; i++) {
    
    
        parent[i] = i;
    }
    for (int i = 0; i < connectionsSize; i++) {
    
    
        int root_x = find(parent, connections[i][0]);
        int root_y = find(parent, connections[i][1]);
        if (root_x != root_y) {
    
    
            parent[root_x] = root_y;
            count--;//相连接
        }
    }
    return count - 1;
}

Originally, I thought that there is a way to reduce the amount of calculations in connection and merge, but I forgot how to calculate it. . . .

Also, I strongly recommend the bilibili video . You have to watch it every time before you check the collection, or it is not uncomfortable.

Insert picture description here

Guess you like

Origin blog.csdn.net/FG_future/article/details/113059090