classSolution:defcountPairs(self, n:int, edges: List[List[int]])->int:d = defaultdict(list)isCnt =set()for i inrange(len(edges)):d[edges[i][0]].append(edges[i][1])d[edges[i][1]].append(edges[i][0])ans =0for i inrange(n):if i in isCnt:continuecnt =1l = d[i]isCnt.add(i)whilelen(l)>0:newl =[]for j in l:if j in isCnt:continuenewl.extend(d[j])cnt +=1isCnt.add(j)l = newl.copy()ans += cnt *(n - cnt)return ans //2