classSolution: defcountPairs(self, n: int, edges: List[List[int]]) -> int: g = [[] for _ inrange(n)] for x, y in edges: g[x].append(y) g[y].append(x)
vis, ans, tot, size = [False] * n, 0, 0, 0 defdfs(x: int) -> None: nonlocal size vis[x] = True size += 1 for y in g[x]: ifnot vis[y]: dfs(y) for i inrange(n): ifnot vis[i]: size = 0 dfs(i) ans += size * tot tot += size return ans
classSolution { List<Integer>[] g; boolean[] vis; int cnt;
publiclongcountPairs(int n, int[][] edges) { g = newArrayList[n]; Arrays.setAll(g, e -> newArrayList<>()); for (var e : edges) { intx= e[0], y = e[1]; g[x].add(y); g[y].add(x); } vis = newboolean[n]; varans=0L; for (inti=0, tot = 0; i < n; ++i) if (!vis[i]) { cnt = 0; dfs(i); ans += (long) cnt * tot; tot += cnt; } return ans; }
voiddfs(int x) { vis[x] = true; ++cnt; for (var y : g[x]) if (!vis[y]) dfs(y); } }
classSolution { public: longlongcountPairs(int n, vector<vector<int>> &edges){ vector<vector<int>> g(n); for (auto &e : edges) { int x = e[0], y = e[1]; g[x].push_back(y); g[y].push_back(x); }
bool vis[n]; memset(vis, 0, sizeof(vis)); long ans = 0L; int cnt = 0; function<void(int)> dfs = [&](int x) { vis[x] = true; ++cnt; for (int y: g[x]) if (!vis[y]) dfs(y); }; for (int i = 0, tot = 0; i < n; ++i) if (!vis[i]) { cnt = 0; dfs(i); ans += (long) cnt * tot; tot += cnt; } return ans; } };
funccountPairs(n int, edges [][]int) (ans int64) { g := make([][]int, n) for _, e := range edges { x, y := e[0], e[1] g[x] = append(g[x], y) g[y] = append(g[y], x) }
vis := make([]bool, n) tot, size := 0, 0 var dfs func(int) dfs = func(x int) { vis[x] = true size++ for _, y := range g[x] { if !vis[y] { dfs(y) } } } for i, b := range vis { if !b { size = 0 dfs(i) ans += int64(size) * int64(tot) tot += size } } return }