当前位置:网站首页>leetcode 统计无向图中无法互相到达点对数
leetcode 统计无向图中无法互相到达点对数
2022-06-29 02:29:00 【我很忙2010】
给你一个整数 n ,表示一张 无向图 中有 n 个节点,编号为 0 到 n - 1 。同时给你一个二维整数数组 edges ,其中 edges[i] = [ai, bi] 表示节点 ai 和 bi 之间有一条 无向 边。
请你返回 无法互相到达 的不同 点对数目 。
示例 1:

输入:n = 3, edges = [[0,1],[0,2],[1,2]] 输出:0 解释:所有点都能互相到达,意味着没有点对无法互相到达,所以我们返回 0 。
示例 2:

输入:n = 7, edges = [[0,2],[0,5],[2,4],[1,6],[5,4]] 输出:14 解释:总共有 14 个点对互相无法到达: [[0,1],[0,3],[0,6],[1,2],[1,3],[1,4],[1,5],[2,3],[2,6],[3,4],[3,5],[3,6],[4,6],[5,6]] 所以我们返回 14 。
提示:
1 <= n <= 1050 <= edges.length <= 2 * 105edges[i].length == 20 <= ai, bi < nai != bi- 不会有重复边。
C++
class Solution {
public:
int find(int x) {
if(pre[x]==x) {
return x;
}
int y=pre[x];
int root=find(y);
pre[x]=root;
return root;
}
long long countPairs(int n, vector<vector<int>>& edges) {
pre.resize(n);
for(int i=0;i<n;i++) {
pre[i]=i;
}
for(auto e:edges) {
int x=e[0];
int y=e[1];
int root1=find(x);
int root2=find(y);
if(root1!=root2) {
pre[root2]=root1;
}
}
unordered_map<int,long> mp;
for(int i=0;i<n;i++) {
int root=find(i);
mp[root]++;
}
long res=(long)n*(long)(n-1)/2;
for(auto it:mp) {
res-=it.second*(it.second-1)/2;
}
return res;
}
private:
vector<int> pre;
};边栏推荐
- [learning notes] subsets and questions
- String output
- SAP ui5 beginner tutorial 22 - development and use of filter
- 高并发的理解与设计方案
- The linkedhashset set makes the elements orderly without repetition
- Is it safe to contact the account manager online to open an account for stock speculation?
- Table implements alternative adaptation through pseudo classes
- [redis] set type
- String method exercise
- 月薪没到30K的程序员必须要背的面试八股,我先啃为敬
猜你喜欢
随机推荐
Dialogue with opensea co creation Alex: we still only touch the tip of the iceberg of NFT capability | chain catcher
Wechat campaign auto like
What is the dry goods microservice architecture? What are the advantages and disadvantages?
String method exercise
Chrome browser close update Popup
Blog publishing test 2
Studies of relative costs for development in different languages
String segment combination
Deploy redis high availability cluster
fsockopen函数的应用
Temperature conversion II
安装mysql5.7 并修改密码
月薪没到30K的程序员必须要背的面试八股,我先啃为敬
大三下期末考试
Is the ETF fund reliable and safe
B1009 irony
字符串输出
Use photoshop2022 to create a wonderful gradient effect for pictures
Blog publishing test 1
Why should the pointer be null after delete




![[redis] sortedset type](/img/7f/f5f1aa603c8994b669d52a435fed7e.png)




