|
| 1 | +from collections import defaultdict |
| 2 | + |
| 3 | +n, m = map(int, input().split()) |
| 4 | +ab = [] |
| 5 | +for _ in range(m): |
| 6 | + a, b = map(int, input().split()) |
| 7 | + ab.append((a - 1, b - 1)) |
| 8 | + |
| 9 | +class UnionFind(): |
| 10 | + def __init__(self, n): |
| 11 | + self.n = n + 1 |
| 12 | + self.parents = [-1] * (n + 1) |
| 13 | + |
| 14 | + def find(self, x): |
| 15 | + if self.parents[x] < 0: |
| 16 | + return x |
| 17 | + else: |
| 18 | + self.parents[x] = self.find(self.parents[x]) |
| 19 | + return self.parents[x] |
| 20 | + |
| 21 | + def union(self, x, y): |
| 22 | + x = self.find(x) |
| 23 | + y = self.find(y) |
| 24 | + |
| 25 | + if x == y: |
| 26 | + return |
| 27 | + |
| 28 | + if self.parents[x] > self.parents[y]: |
| 29 | + x, y = y, x |
| 30 | + |
| 31 | + self.parents[x] += self.parents[y] |
| 32 | + self.parents[y] = x |
| 33 | + |
| 34 | + def size(self, x): |
| 35 | + return -self.parents[self.find(x)] |
| 36 | + |
| 37 | + def same(self, x, y): |
| 38 | + return self.find(x) == self.find(y) |
| 39 | + |
| 40 | + def members(self, x): |
| 41 | + root = self.find(x) |
| 42 | + return [i for i in range(self.n) if self.find(i) == root] |
| 43 | + |
| 44 | + def roots(self): |
| 45 | + return [i for i, x in enumerate(self.parents) if x < 0] |
| 46 | + |
| 47 | + def group_count(self): |
| 48 | + return len(self.roots()) |
| 49 | + |
| 50 | + def all_group_members(self): |
| 51 | + return {r: self.members(r) for r in self.roots()} |
| 52 | + |
| 53 | + def __str__(self): |
| 54 | + return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots()) |
| 55 | + |
| 56 | +uf_tree = UnionFind(n=n) |
| 57 | + |
| 58 | +for a, b in ab: |
| 59 | + uf_tree.union(a, b) |
| 60 | + |
| 61 | +group_counts = defaultdict(int) |
| 62 | + |
| 63 | +for i in range(n): |
| 64 | + group = uf_tree.find(i) |
| 65 | + group_counts[group] += 1 |
| 66 | + |
| 67 | +path_count = defaultdict(int) |
| 68 | +for a, _ in ab: |
| 69 | + group = uf_tree.find(a) |
| 70 | + path_count[group] += 1 |
| 71 | + |
| 72 | +ans = 0 |
| 73 | +for group in group_counts.keys(): |
| 74 | + ans += group_counts[group] * (group_counts[group] - 1) // 2 |
| 75 | + ans -= path_count[group] |
| 76 | + |
| 77 | +print(ans) |
0 commit comments