← Home

1595. Minimum Cost to Connect Two Groups of Points

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
DFS + memoizationC++Markdown
159

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 1595. Minimum Cost to Connect Two Groups of Points, the solution in this repository is mainly a DFS + memoization 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: DFS + memoization, graph traversal, dynamic programming, greedy.

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

  • dfs + memorization, greedy
  • https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/discuss/855041/C%2B%2BPython-DP-using-mask
  • vector version
  • ARR version

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are dfs, connectTwoGroups, min_g2.

Guide

Why?

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

  • 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(m*2^n * n), it takes O(n) to compute each state
  • Space: O(m*2^n)

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//dfs + memorization, greedy
02//https://leetcode.com/problems/minimum-cost-to-connect-two-groups-of-points/discuss/855041/C%2B%2BPython-DP-using-mask
03//vector version
04//Runtime: 64 ms, faster than 51.35% of C++ online submissions for Minimum Cost to Connect Two Groups of Points.
05//Memory Usage: 26.8 MB, less than 11.50% of C++ online submissions for Minimum Cost to Connect Two Groups of Points.
06//ARR version
07//Runtime: 36 ms, faster than 75.04% of C++ online submissions for Minimum Cost to Connect Two Groups of Points.
08//Memory Usage: 8.6 MB, less than 71.21% of C++ online submissions for Minimum Cost to Connect Two Groups of Points.
09//ARR version: visited element in memo will always be >= 1, so we don't need to initialize memo as -1
10//m: size of group1, n: size of group2
11//time: O(m*2^n * n), it takes O(n) to compute each state
12//space: O(m*2^n)
13class Solution {
14public:
15    int m, n;
16
17#define ARR
18#ifdef ARR
19    int memo[13][1<<12];
20#else
21    vector<vector<int>> memo;
22#endif
23    
24    int dfs(vector<vector<int>>& cost, vector<int>& min_g2, int i, int mask){
25#ifdef ARR
26        if(memo[i][mask] != 0){
27            return memo[i][mask]-1;
28#else
29        if(memo[i][mask] != -1){
30            return memo[i][mask];
31#endif
32        }else if(i == m){
33            int res = 0;
34            
35            for(int j = 0; j < n; ++j){
36                //if j is not connected
37                if(!(mask & (1<<j))){
38                    res += min_g2[j];
39                }
40            }
41#ifdef ARR
42            memo[i][mask] = res + 1;
43#else
44            memo[i][mask] = res;
45#endif
46            return res;
47        }else{
48            int res = INT_MAX;
49            
50            for(int j = 0; j < n; ++j){
51                res = min(res, 
52                    cost[i][j] + dfs(cost, min_g2, i+1, mask | (1 << j)));
53            }
54#ifdef ARR
55            memo[i][mask] = res + 1;
56#else
57            memo[i][mask] = res;
58#endif
59            return res;
60        }
61    }
62    
63    int connectTwoGroups(vector<vector<int>>& cost) {
64        m = cost.size();
65        n = cost[0].size();
66        
67        vector<int> min_g2(n, INT_MAX);
68        
69        for(int j = 0; j < n; ++j){
70            for(int i = 0; i < m; ++i){
71                min_g2[j] = min(min_g2[j], cost[i][j]);
72            }
73        }
74
75#ifndef ARR
76        memo = vector<vector<int>>(m+1, vector<int>(1<<12, -1));
77#endif
78        
79        return dfs(cost, min_g2, 0, 0);
80    }
81};

Cost

Complexity

Time
O(m*2^n * n), it takes O(n) to compute each state
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(m*2^n)
Auxiliary state plus the answer structure where the problem requires one.