codekofi
← All problems

Problem 77

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

1int solution(const vector<vector<int>>& times, int n, int start) {
2
3 vector<vector<pair<int, int>>> wires(n + 1);
4
5 for (const auto& t : times) {
6 wires[t[0]].push_back({t[1], t[2]});
7 }
8
9 vector<int> best(n + 1, INT_MAX);
10 best[start] = 0;
11
12 using Step = pair<int, int>;
13 priority_queue<Step, vector<Step>, greater<Step>> heap;
14 heap.push({0, start});
15
16 while (!heap.empty()) {
17
18 auto [cost, node] = heap.top();
19 heap.pop();
20
21 if (cost > best[node]) {
22 continue;
23 }
24
25 for (auto [other, weight] : wires[node]) {
26
27 int total = cost + weight;
28
29 if (total < best[other]) {
30 best[other] = total;
31 heap.push({total, other});
32 }
33 }
34 }
35
36 int worst = 0;
37
38 for (int i = 1; i <= n; i++) {
39
40 if (best[i] == INT_MAX) {
41 return -1;
42 }
43
44 worst = max(worst, best[i]);
45 }
46
47 return worst;
48}

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.