← Home

1494. Parallel Courses II

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
149

Let's make this one less mysterious. For 1494. Parallel Courses II, the solution in this repository is mainly a dynamic programming 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: dynamic programming, bit manipulation.

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

  • WA
  • 29 / 53 test cases passed.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are minNumberOfSemesters, visited, pre.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • 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. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

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//WA
02//29 / 53 test cases passed.
03class Solution {
04public:
05    int minNumberOfSemesters(int n, vector<vector<int>>& dependencies, int k) {
06        vector<bool> visited(n+1, false);
07        set<int> sources;
08        vector<vector<int>> edges(n+1);
09        set<int>::iterator it;
10        
11        for(int i = 1; i <= n; ++i){
12            sources.insert(i);
13        }
14        
15        for(vector<int> dep : dependencies){
16            if((it = sources.find(dep[1])) != sources.end()){
17                sources.erase(it);
18            }
19            edges[dep[0]].push_back(dep[1]);
20        }
21        
22        /*
23        cout << "sources: ";
24        for(const int& source : sources){
25            cout << source << " ";
26        }
27        cout << endl;
28        */
29        
30        int ans = 0;
31        
32        set<int> next_sources;
33        while(!sources.empty()){
34            /*
35            cout << "sources: ";
36            for(const int& source : sources){
37                cout << source << " ";
38            }
39            cout << endl;
40            cout << "add: " << ceil((double)sources.size()/k) << endl;
41            */
42            ans += ceil((double)sources.size()/k);
43            for(int source : sources){
44                next_sources.insert(edges[source].begin(), edges[source].end());
45            }
46            swap(sources, next_sources);
47            next_sources.clear();
48        }
49        
50        
51        return ans;
52    }
53};
54
55//dp, bitmask
56//https://leetcode.com/problems/parallel-courses-ii/discuss/708263/Can-anyone-explain-the-bit-mask-method
57//Runtime: 440 ms, faster than 13.11% of C++ online submissions for Parallel Courses II.
58//Memory Usage: 8.3 MB, less than 83.33% of C++ online submissions for Parallel Courses II.
59class Solution {
60public:
61    int minNumberOfSemesters(int n, vector<vector<int>>& dependencies, int k) {
62        /*
63        prerequisite of n courses
64        if course i is dependent on course j,
65        then pre[i]'s jth bit will be set
66        */
67        vector<int> pre(n);
68        
69        for(vector<int>& dep : dependencies){
70            pre[dep[1]-1] |= (1 << (dep[0]-1));
71        }
72        
73        /*
74        key: the combination of courses(bit representation)
75        value: minimum days to take all the courses
76        */
77        vector<int> dp(1<<n, n);
78        
79        //require 0 days to take 0 courses
80        dp[0] = 0;
81        
82        /*
83        need to go into the loop even if cur is 0,
84        because in there we will update dp[cur|subnext]!
85        */
86        for(int cur = 0; cur < (1<<n); ++cur){
87            /*
88            if we have taken all courses specified by "cur",
89            we can take the courses specified by "next"
90            */
91            int next = 0;
92            
93            for(int j = 0; j < n; ++j){
94                /*
95                if we have taken all prerequisites of course "j",
96                we can then take course "j" now
97                */
98                if((cur & pre[j]) == pre[j]){
99                    /*
100                    cur is the superset of pre[j],
101                    that means in current state,
102                    we have taken all prerequisites of course j
103                    */
104                    next |= (1<<j);
105                }
106            }
107            
108            /*
109            now "next" specify the course we are able to taken,
110            but we don't need to take the courses that are already taken
111            (which are specified by cur)
112            so ""&= ~cur" to exclude those courses
113            */
114            next &= ~cur;
115            
116            /*
117            https://cp-algorithms.com/algebra/all-submasks.html
118            enumerate all the bit 1 combinations(submask)?
119            */
120            for(int subnext = next; subnext; subnext = (subnext-1) & next){
121                if(__builtin_popcount(subnext) <= k){
122                    //we can take at most k courses in a day
123                    dp[cur|subnext] = min(dp[cur|subnext], dp[cur]+1);
124                }
125            }
126        }
127        
128        return dp.back();
129    }
130};

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.