← Home

1579. Remove Max Number of Edges to Keep Graph Fully Traversable

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
union-findC++Markdown
157

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 1579. Remove Max Number of Edges to Keep Graph Fully Traversable, the solution in this repository is mainly a union-find solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: union-find, greedy.

The notes already sitting in the source point us in the right direction:

  • Union find
  • originally thought as a graph problem
  • hint: Always use Type 3 edges first, and connect the still isolated ones using other edges.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are unite, maxNumEdgesToRemove.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Union find
02//originally thought as a graph problem
03//hint: Always use Type 3 edges first, and connect the still isolated ones using other edges.
04//Runtime: 1236 ms, faster than 75.00% of C++ online submissions for Remove Max Number of Edges to Keep Graph Fully Traversable.
05//Memory Usage: 139 MB, less than 50.00% of C++ online submissions for Remove Max Number of Edges to Keep Graph Fully Traversable.
06class DSU{
07public:
08    int n;
09    vector<int> parent;
10    vector<int> sz;
11    int max_sz;
12    
13    DSU(int n){
14        this->n = n;
15        parent = vector<int>(n);
16        iota(parent.begin(), parent.end(), 0);
17        sz = vector<int>(n, 1);
18        max_sz = 1;
19    }
20    
21    int find(int x){
22        if(parent[x] != x){
23            parent[x] = find(parent[x]);
24        }
25        return parent[x];
26    }
27    
28    int unite(int x, int y){
29        if(x > y) swap(x, y);
30        //merge the later to the earlier
31        
32        int py = find(y);
33        int px = find(x);
34        
35        if(px == py)
36            return -1;
37        
38        parent[py] = px;
39        sz[px] += sz[py];
40        max_sz = max(max_sz, sz[px]);
41        
42        return 0;
43    }
44};
45
46class Solution {
47public:
48    int maxNumEdgesToRemove(int n, vector<vector<int>>& edges) {
49        sort(edges.begin(), edges.end(), 
50            [](vector<int>& e1, vector<int>& e2){return e1[0] > e2[0];});
51        
52        DSU dsu1(n), dsu2(n);
53        int discarded = 0;
54        
55        for(vector<int>& edge : edges){
56            // cout << edge[0] << ", " << edge[1] << ", " << edge[2] << endl;
57            switch(edge[0]){
58                case 1:
59                    if(dsu1.unite(edge[1]-1, edge[2]-1)){
60                        ++discarded;
61                        // cout << "discard" << endl;
62                    }
63                    // cout << "dsu1 max size: " << dsu1.max_sz << endl;
64                    break;
65                case 2:
66                    if(dsu2.unite(edge[1]-1, edge[2]-1)){
67                        ++discarded;
68                        // cout << "discard" << endl;
69                    }
70                    // cout << "dsu2 max size: " << dsu2.max_sz << endl;
71                    break;
72                case 3:
73                    int ret = dsu1.unite(edge[1]-1, edge[2]-1);
74                    dsu2.unite(edge[1]-1, edge[2]-1);
75                    
76                    if(ret){
77                        //they are originally in the same union
78                        //since dsu1 is the same as dsu2 when processing type 3,
79                        //so only need to check dsu1
80                        ++discarded;
81                        // cout << "discard" << endl;
82                    }
83                    // cout << "max size: " << dsu1.max_sz << endl;
84            }
85        }
86        
87        if(dsu1.max_sz != n || dsu2.max_sz != n){
88            //the graph is not fully connected
89            return -1;
90        }
91        
92        return discarded;
93    }
94};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.