博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
力扣题解-1319. 连通网络的操作次数(并查集)
阅读量:4299 次
发布时间:2019-05-27

本文共 2293 字,大约阅读时间需要 7 分钟。

题目:1319. 连通网络的操作次数

用以太网线缆将 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

提示:

1 <= n <= 10^5
1 <= connections.length <= min(n*(n-1)/2, 10^5)
connections[i].length == 2
0 <= connections[i][0], connections[i][1] < n
connections[i][0] != connections[i][1]
没有重复的连接。
两台计算机不会通过多条线缆连接。

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/number-of-operations-to-make-network-connected
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

可以直接将网络看作是图论中的问题,本题要解决的问题是将给定的图转换成连通图需要修改边的次数。

因此,我们只要得到图的最大连通分量个数,就可以得到答案(连通分量个数 - 1)。

求最大连通分量个数,可以用并查集实现。

代码

class Solution {
class UnionFind {
int n; vector
parent; public: UnionFind(int n_): n(n_) {
parent.resize(n); for(int i = 0; i < n; i++) {
parent[i] = i; } } int find(int x) {
int root = x; while(root != parent[root]) {
root = parent[root]; } while(x != parent[x]) {
int tmp = parent[x]; parent[x] = root; x = tmp; } return root; } void merge(int x, int y) {
int px = find(x); int py = find(y); if(px == py) {
return; } parent[py] = px; n--; } int getSetNum(void) {
return n; } };public: int makeConnected(int n, vector
>& connections) {
if(connections.size() < n - 1) {
return -1; } UnionFind unionFind(n); for(int i = 0; i < connections.size(); i++) {
int x = connections[i][0]; int y = connections[i][1]; unionFind.merge(x, y); } return unionFind.getSetNum() - 1; }};
你可能感兴趣的文章
通知机制 (Notifications)
查看>>
10 Things You Need To Know About Cocoa Auto Layout
查看>>
C指针声明解读之左右法则
查看>>
一个异步网络请求的坑:关于NSURLConnection和NSRunLoopCommonModes
查看>>
iOS 如何放大按钮点击热区
查看>>
ios设备唯一标识获取策略
查看>>
获取推送通知的DeviceToken
查看>>
Could not find a storyboard named 'Main' in bundle NSBundle
查看>>
CocoaPods安装和使用教程
查看>>
Beginning Auto Layout Tutorial
查看>>
block使用小结、在arc中使用block、如何防止循环引用
查看>>
iPhone开发学习笔记002——Xib设计UITableViewCell然后动态加载
查看>>
iOS开发中遇到的问题整理 (一)
查看>>
Swift code into Object-C 出现 ***-swift have not found this file 的问题
查看>>
为什么你的App介绍写得像一坨翔?
查看>>
RTImageAssets插件--@3x可自动生成@2x图片
查看>>
iOS开发的一些奇巧淫技
查看>>
常浏览的博客和网站
查看>>
Xcode 工程文件打开不出来, cannot be opened because the project file cannot be parsed.
查看>>
点击button实现Storyboard中TabBar Controller的tab切换
查看>>