voidUnionCa(int x, int y){ int fx = findFa(x), fy = findFa(y); if (fx != fy) { if (sizes[fx] > sizes[fy]) { fa[fy] = fx; sizes[fx] += sizes[fy]; } else { fa[fx] = fy; sizes[fy] += sizes[fx]; } } } };
classSolution { public: longlongcountPairs(int n, vector<vector<int>>& edges){ Union myu(n); for (auto &edge : edges) { myu.UnionCa(edge[0], edge[1]); } longlong res = 0; for (int i = 0; i < n; i++) { res += n - myu.sizes[myu.findFa(i)]; } return res / 2; // 每个点对会被算两次,所以/2 } };