codekofi
← All problems

Problem 132

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
9vector<int> solution(const vector<vector<int>>& edges) {
10
11 int n = edges.size();
12 vector<int> owner(n + 1);
13
14 for (int i = 0; i <= n; i++) {
15 owner[i] = i;
16 }
17
18 for (const auto& e : edges) {
19
20 int a = root(owner, e[0]);
21 int b = root(owner, e[1]);
22
23 if (a == b) {
24 return e;
25 }
26
27 owner[a] = b;
28 }
29
30 return {};
31}

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.