← Home

1466. Reorder Routes to Make All Paths Lead to the City Zero

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

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 1466. Reorder Routes to Make All Paths Lead to the City Zero, the solution in this repository is mainly a union-find solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. 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.

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are unite, minReorder, visited.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • 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//Runtime: 412 ms, faster than 98.38% of C++ online submissions for Reorder Routes to Make All Paths Lead to the City Zero.
02//Memory Usage: 67.4 MB, less than 100.00% of C++ online submissions for Reorder Routes to Make All Paths Lead to the City Zero.
03class DSU{
04public:
05    vector<int> parent;
06    
07    DSU(int N){
08        parent = vector<int>(N);
09        iota(parent.begin(), parent.end(), 0);
10    }
11    
12    int find(int x){
13        if(parent[x] != x){ //initial state
14            parent[x] = find(parent[x]);
15        }
16        return parent[x];
17    }
18    
19    void unite(int x, int y){
20        // not "parent[x] = find(parent[y]);"
21        // not "parent[y] = find(parent[x]);"
22        // combine two component's head together
23        parent[find(x)] = find(y);
24    }
25};
26
27class Solution {
28public:
29    int minReorder(int n, vector<vector<int>>& connections) {
30        DSU dsu(n);
31        int ans = 0;
32        
33        vector<bool> visited(connections.size(), false);
34        
35        while(any_of(visited.begin(), visited.end(), [](const bool& b){return !b;})){
36            for(int i = 0; i < connections.size(); i++){
37                if(visited[i]) continue;
38                vector<int> conn = connections[i];
39                // cout << conn[0] << ", " << conn[1] << " : " << dsu.parent[conn[0]] << ", " << dsu.parent[conn[1]] << endl;
40                if(dsu.parent[conn[0]] == 0){
41                    dsu.unite(conn[1], conn[0]);
42                    ans++;
43                    visited[i] = true;
44                }else if(dsu.parent[conn[1]] == 0){
45                    dsu.unite(conn[0], conn[1]);  
46                    visited[i] = true; 
47                }
48            }
49            // std::cout << count_if(visited.begin(), visited.end(), [](const bool& b){return !b;}) << " not visited." << endl;
50        }
51        
52        
53        // for(int i = 0; i < n; i++){
54        //     cout << i << " : " << dsu.parent[i] << endl;
55        // }
56        
57        return ans;
58    }
59};

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.