codekofi
← All problems

Problem 46

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1bool solution(int n, const vector<vector<int>>& pairs) {
2
3 vector<vector<int>> unlocks(n);
4 vector<int> waiting(n, 0);
5
6 for (const auto& p : pairs) {
7 unlocks[p[1]].push_back(p[0]);
8 waiting[p[0]]++;
9 }
10
11 queue<int> ready;
12
13 for (int i = 0; i < n; i++) {
14 if (waiting[i] == 0) {
15 ready.push(i);
16 }
17 }
18
19 int taken = 0;
20
21 while (!ready.empty()) {
22
23 int course = ready.front();
24 ready.pop();
25 taken++;
26
27 for (int other : unlocks[course]) {
28
29 waiting[other]--;
30
31 if (waiting[other] == 0) {
32 ready.push(other);
33 }
34 }
35 }
36
37 return taken == n;
38}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.