|
| 1 | +struct UnionSet { |
| 2 | + parent: Vec<usize>, |
| 3 | + depth: Vec<usize>, |
| 4 | +} |
| 5 | + |
| 6 | +impl UnionSet { |
| 7 | + fn new(node_count: usize) -> Self { |
| 8 | + let mut initial_set = UnionSet { |
| 9 | + parent: vec![0; node_count], |
| 10 | + depth: vec![0; node_count], |
| 11 | + }; |
| 12 | + for node in 0..node_count { |
| 13 | + initial_set.parent[node]= node; |
| 14 | + } |
| 15 | + initial_set |
| 16 | + } |
| 17 | + |
| 18 | + fn unite(&mut self, node1: usize, node2: usize) { |
| 19 | + let parent1 = self.find_most_parent(node1); |
| 20 | + let parent2 = self.find_most_parent(node2); |
| 21 | + |
| 22 | + if self.depth[parent1] == self.depth[parent2] { |
| 23 | + self.depth[parent2] += 1; |
| 24 | + self.parent[parent1] = parent2; |
| 25 | + } else if self.depth[parent1] > self.depth[parent2] { |
| 26 | + self.parent[parent2] = parent1; |
| 27 | + } else { |
| 28 | + self.parent[parent1] = parent2; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + fn find_most_parent(&mut self, node: usize) -> usize { |
| 33 | + let mut parent_node = self.parent[node]; |
| 34 | + while self.parent[parent_node] != parent_node { |
| 35 | + parent_node = self.parent[parent_node]; |
| 36 | + } |
| 37 | + self.parent[node] = parent_node; |
| 38 | + parent_node |
| 39 | + } |
| 40 | + |
| 41 | + fn comp(&mut self, node1: usize, node2: usize) -> bool { |
| 42 | + self.find_most_parent(node1) == self.find_most_parent(node2) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +fn main() { |
| 47 | + let input_info: Vec<usize> = input::read_numline(); |
| 48 | + let node_count = input_info[0]; |
| 49 | + let operation_count = input_info[1]; |
| 50 | + let mut union_set = UnionSet::new(node_count); |
| 51 | + let mut result_vec: Vec<bool> = vec![]; |
| 52 | + |
| 53 | + for _ in 0..operation_count { |
| 54 | + let operation: Vec<usize> = input::read_numline(); |
| 55 | + if operation[0] == 0 { |
| 56 | + let unite_node1 = operation[1]; |
| 57 | + let unite_node2 = operation[2]; |
| 58 | + union_set.unite(unite_node1, unite_node2); |
| 59 | + } else { |
| 60 | + let findparent_node1 = operation[1]; |
| 61 | + let findparent_node2 = operation[2]; |
| 62 | + let result = union_set.comp(findparent_node1, findparent_node2); |
| 63 | + result_vec.push(result); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + for result in &result_vec { |
| 68 | + if *result { |
| 69 | + println!("1"); |
| 70 | + } else { |
| 71 | + println!("0"); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments