|
| 1 | +import sys |
| 2 | + |
| 3 | +read = lambda: sys.stdin.readline().rstrip() |
| 4 | + |
| 5 | + |
| 6 | +class Problem: |
| 7 | + def __init__(self): |
| 8 | + self.n = int(read()) |
| 9 | + self.planets = [] |
| 10 | + |
| 11 | + for idx in range(self.n): |
| 12 | + x, y, z = map(int, read().split()) |
| 13 | + self.planets.append((idx, x, y, z)) |
| 14 | + |
| 15 | + self.roots = [x for x in range(self.n)] |
| 16 | + |
| 17 | + def solve(self) -> None: |
| 18 | + print(self.find_minimum_cost()) |
| 19 | + |
| 20 | + def find_minimum_cost(self) -> int: |
| 21 | + edges, weight = self.find_edges(), 0 |
| 22 | + |
| 23 | + for distance, src, dest in edges: |
| 24 | + if self.union(src, dest): |
| 25 | + weight += distance |
| 26 | + |
| 27 | + return weight |
| 28 | + |
| 29 | + def find_edges(self) -> list[tuple[int, int, int]]: |
| 30 | + edges = [] |
| 31 | + for axis in range(1, 4): |
| 32 | + self.planets.sort(key=lambda planet: planet[axis]) |
| 33 | + |
| 34 | + for idx in range(self.n - 1): |
| 35 | + edges.append( |
| 36 | + ( |
| 37 | + abs(self.planets[idx][axis] - self.planets[idx + 1][axis]), |
| 38 | + self.planets[idx][0], |
| 39 | + self.planets[idx + 1][0], |
| 40 | + ) |
| 41 | + ) |
| 42 | + |
| 43 | + return sorted(edges) |
| 44 | + |
| 45 | + def union(self, src: int, dest: int) -> bool: |
| 46 | + src_root, dest_root = self.find_root(src), self.find_root(dest) |
| 47 | + if src_root == dest_root: |
| 48 | + return False |
| 49 | + |
| 50 | + self.roots[src_root] = dest_root |
| 51 | + return True |
| 52 | + |
| 53 | + def find_root(self, num: int) -> int: |
| 54 | + while num != self.roots[num]: |
| 55 | + self.roots[num] = self.roots[self.roots[num]] |
| 56 | + num = self.roots[num] |
| 57 | + |
| 58 | + return num |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + Problem().solve() |
0 commit comments