codekofi
← All problems

Problem 38

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 gap(int a, int b) {
2
3 if (a > b) {
4 return a - b;
5 }
6
7 return b - a;
8}
9
10int solution(const vector<vector<int>>& points) {
11
12 int n = points.size();
13
14 if (n <= 1) {
15 return 0;
16 }
17
18 vector<bool> joined(n, false);
19 vector<int> best(n, INT_MAX);
20
21 best[0] = 0;
22 int total = 0;
23
24 for (int step = 0; step < n; step++) {
25
26 int pick = -1;
27
28 for (int i = 0; i < n; i++) {
29
30 if (joined[i]) {
31 continue;
32 }
33
34 if (pick < 0 || best[i] < best[pick]) {
35 pick = i;
36 }
37 }
38
39 joined[pick] = true;
40 total += best[pick];
41
42 for (int i = 0; i < n; i++) {
43
44 if (joined[i]) {
45 continue;
46 }
47
48 int dx = gap(points[i][0], points[pick][0]);
49 int dy = gap(points[i][1], points[pick][1]);
50
51 best[i] = min(best[i], dx + dy);
52 }
53 }
54
55 return total;
56}

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.