codekofi
← All problems

Problem 96

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

1vector<int> 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 vector<int> order;
20
21 while (!ready.empty()) {
22
23 int course = ready.front();
24 ready.pop();
25
26 order.push_back(course);
27
28 for (int other : unlocks[course]) {
29
30 waiting[other]--;
31
32 if (waiting[other] == 0) {
33 ready.push(other);
34 }
35 }
36 }
37
38 if ((int)order.size() != n) {
39 return {};
40 }
41
42 return order;
43}

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.