原题链接:
https://leetcode.cn/problems/count-unreachable-pairs-of-nodes-in-an-undirected-graph/description/
解法1: 并查集
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| typedef long long LL;
class Solution { public: vector<int>p; unordered_map<int,int>cnt;
int find(int x){ if(x!=p[x]){ p[x] = find(p[x]); } return p[x]; }
void merge(int x,int y){ int a = find(x); int b = find(y);
if(a <= b){ p[a] = b; }else{ p[b] = a; }
}
long long countPairs(int n, vector<vector<int>>& edges) { p.resize(n);
for(int i = 0; i < n ; i++){ p[i] = i; }
for(auto e: edges){ merge(e[0],e[1]); }
for(int i = 0 ; i < n ; i++){ int root = find(i); cnt[root] = cnt[root] + 1; }
LL ans = 0;
for(auto [k,v] : cnt){ ans += 1L * (n - v) * v; }
return ans/2; } };
|
解法2: DFS