codekofi
← All problems

Problem 147

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 root(vector<int>& owner, int x) {
2 while (owner[x] != x) {
3 owner[x] = owner[owner[x]];
4 x = owner[x];
5 }
6 return x;
7}
8
9bool solution(int n, const vector<vector<int>>& edges) {
10
11 if (n == 0) {
12 return true;
13 }
14
15 if ((int)edges.size() != n - 1) {
16 return false;
17 }
18
19 vector<int> owner(n);
20
21 for (int i = 0; i < n; i++) {
22 owner[i] = i;
23 }
24
25 for (const auto& e : edges) {
26
27 int a = root(owner, e[0]);
28 int b = root(owner, e[1]);
29
30 if (a == b) {
31 return false;
32 }
33
34 owner[a] = b;
35 }
36
37 return true;
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.