当前位置:网站首页>leetcode-1319:连通网络的操作次数
leetcode-1319:连通网络的操作次数
2022-07-30 17:38:00 【菊头蝙蝠】
题目
用以太网线缆将 n 台计算机连接成一个网络,计算机的编号从 0 到 n-1。线缆用 connections 表示,其中 connections[i] = [a, b] 连接了计算机 a 和 b。
网络中的任何一台计算机都可以通过网络直接或者间接访问同一个网络中其他任意一台计算机。
给你这个计算机网络的初始布线 connections,你可以拔开任意两台直连计算机之间的线缆,并用它连接一对未直连的计算机。请你计算并返回使所有计算机都连通所需的最少操作次数。如果不可能,则返回 -1 。
示例 1:

输入:n = 4, connections = [[0,1],[0,2],[1,2]]
输出:1
解释:拔下计算机 1 和 2 之间的线缆,并将它插到计算机 1 和 3 上。
示例 2:

输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
输出:2
示例 3:
输入:n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
输出:-1
解释:线缆数量不足。
示例 4:
输入:n = 5, connections = [[0,1],[0,2],[3,4],[2,3]]
输出:0
解题
方法一:并查集
比如有n台电脑,如果连接线数小于n-1,那么一定是没法成功的。
如果连线数大于等于n-1,那么一定可以通过一定的修改,以此来修改成功由于连接数大于等于n-1则一定可以修改成功,那么可以使用并查集,得到最后剩下的集合个数m,那么最后需要修改的,就需要m-1根即可。
class UnionFind{
private:
vector<int> parent;
int setNum;
public:
UnionFind(int n){
parent.resize(n);
iota(parent.begin(),parent.end(),0);
setNum=n;
}
int find(int index){
if(parent[index]==index) return index;
return parent[index]=find(parent[index]);
}
void unite(int index1,int index2){
int p1=find(index1);
int p2=find(index2);
if(p1!=p2){
parent[p1]=p2;
setNum--;
}
}
int getSetNum(){
return setNum;
}
};
class Solution {
public:
int makeConnected(int n, vector<vector<int>>& connections) {
if(connections.size()<n-1) return -1;//n台电脑,至少需要n-1条线,否则不可能成功
UnionFind uf(n);
for(vector<int>& conn:connections){
uf.unite(conn[0],conn[1]);
}
return uf.getSetNum()-1;//如果还剩下m个集合,那么修改m-1条线
}
};
边栏推荐
- Insert data into MySQL in C language
- 基于模糊PID的液压舵机伺服系统
- 线程同步 控制执行顺序
- 数据库系统原理与应用教程(064)—— MySQL 练习题:操作题 51-61(八):查询条件的构造、通配符
- Mo Team - Elegant Violence
- Summary of String Copy, Concatenation, Comparison and Split Functions (1)
- 数据预处理:离散特征编码方法
- ERROR 2003 (HY000) Can't connect to MySQL server on 'localhost3306' (10061)Solution
- LeetCode318: Maximum product of word lengths
- 592. Fraction Addition and Subtraction
猜你喜欢

升级 MDK 5.37 后的问题处理: AC6编译选项, printf, 重启失效等

952. 按公因数计算最大组件大小 : 枚举质因数 + 并查集运用题

【AAAI2020】阿里DMR:融合Matching思想的深度排序模型

基于模糊PID的液压舵机伺服系统

Servo System of Hydraulic Steering Gear Based on Fuzzy PID

大批程序员可能面临被劝退!

js中的基础知识点 —— BOM

向量检索基础方法总结

Summary of String Copy, Concatenation, Comparison and Split Functions (1)

ERROR 2003 (HY000) Can‘t connect to MySQL server on ‘localhost3306‘ (10061)解决办法
随机推荐
Daily practice------Generate 13-digit bar, Ean-13 code rule: The thirteenth digit is the check code obtained by the calculation of the first twelve digits.
强烈推荐APP破解常用工具集合!
PLSQL Developer安装和配置
华为无线设备Mesh配置命令
C陷阱与缺陷 第7章 可移植性缺陷 7.2 标识符名称的限制
JMeter Notes 4 | JMeter Interface Introduction
编曲软件FL Studio中文版安装教程及切换语言教程
记者卧底
【网络工程】A、B、C、D、E类IP地址划分依据和特殊的IP地址
将 APACHE 日志解析到 SQL 数据库中
Web3时代重要基础设施深度拆解:4EVERLAND
SYSCALL SWAPGS
C陷阱与缺陷 第6章 预处理器 6.2 宏并不是函数
阿里巴巴CAN:Embedding前置的特征交互新思路
ARC在编译期和运行期做了什么
全球架构师峰会
LeetCode318: Maximum product of word lengths
宝塔搭建PHP自适应懒人网址导航源码实测
一个 15 年 SAP ABAP 开发人员分享的 SAPGUI 一些个性化设置和实用小技巧
分账系统二清解决方案如何助力电商平台合规经营?