This code snippet is performing a series of operations on disjoint sets using the union-find algorithm. Here is a breakdown of the code:
1. The code reads two integers `n` and `k` from input and initializes a list called `parent` with values from 0 to `3 * n`. It also initializes a variable `false_count` to keep track of incorrect operations.
2. Two functions `find(x)` and `union(x, y)` are defined:
- The `find(x)` function uses path compression to find the root of the set containing element `x`.
- The `union(x, y)` function unions the sets containing elements `x` and `y` by updating their root nodes in the `parent` list.
3. A loop runs `k` times, parsing input values `d`, `x`, and `y`, adjusting `x` and `y` to be in the range `[0, n-1]`, and performing operations based on the value of `d`:
- If `d` is 1, it checks conditions before performing unions and increments `false_count` if conditions are not met.
- If `d` is 0, it again checks conditions before performing unions and increments `false_count` accordingly.
4. At the end of the loop, the code prints the final value of `false_count`.
In summary, this code implements the union-find algorithm to handle different types of union operations on disjoint sets. The `false_count` variable keeps track of cases where the given operations are invalid. The code is designed to handle cases where elements are merged into different sets based on certain conditions.
1 | n, k = map(int, input().split()) |
2 | parent = list(range(3 * n)) |
3 | false_count = 0 |
4 | |
5 | def find(x): |
6 | if parent[x] != x: |
7 | parent[x] = find(parent[x]) |
8 | return parent[x] |
9 | |
10 | |
11 | def union(x, y): |
12 | root_x = find(x) |
13 | root_y = find(y) |
14 | if root_x != root_y: |
15 | parent[root_y] = root_x |
16 | |
17 | |
18 | for _ in range(k): |
19 | d, x, y = map(int, input().split()) |
20 | x -= 1 |
21 | y -= 1 |
22 | if x < 0 or x >= n or y < 0 or y >= n: |
23 | false_count += 1 |
24 | continue |
25 | if d == 1: |
26 | if find(x) == find(y + n) or find(x) == find(y + 2 * n): |
27 | false_count += 1 |
28 | else: |
29 | union(x, y) |
30 | union(x + n, y + n) |
31 | union(x + 2 * n, y + 2 * n) |
32 | else: |
33 | if x == y or find(x) == find(y) or find(x) == find(y + 2 * n): |
34 | false_count += 1 |
35 | else: |
36 | union(x, y + n) |
37 | union(x + n, y + 2 * n) |
38 | union(x + 2 * n, y) |
39 | |
40 | print(false_count) |