LeetCode 1135. Connecting Cities With Minimum Cost

给定一系列城市的编号和它们之间的距离,本题要求找到连接所有城市使其连通的最小总成本。这是一道最小生成树问题,可以使用Kruskal或Prim算法解决。Kruskal算法先对距离排序,然后逐步连接点;Prim算法从一个节点开始,每次选择最短距离的节点,直至所有节点连接。文中提供了使用UnionFind的Kruskal算法实现,具有较低的时间复杂度。
摘要由CSDN通过智能技术生成

题目

There are N cities numbered from 1 to N.

You are given connections, where each connections[i] = [city1, city2, cost] represents the cost to connect city1 and city2 together.  (A connection is bidirectional: connecting city1 and city2 is the same as connecting city2 and city1.)

Return the minimum cost so that for every pair of cities, there exists a path of connections (possibly of length 1) that connects those two cities together.  The cost is the sum of the connection costs used. If the task is impossible, return -1.

 

Example 1:

Input: N = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
Output: 6
Exp
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值