1135. Connecting Cities With Minimum Cost 连接所有节点的最低价值
2021/8/29 6:08:18
本文主要是介绍1135. Connecting Cities With Minimum Cost 连接所有节点的最低价值,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
There are n
cities labeled from 1
to n
. You are given the integer n
and an array connections
where connections[i] = [xi, yi, costi]
indicates that the cost of connecting city xi
and city yi
(bidirectional connection) is costi
.
Return the minimum cost to connect all the n
cities such that there is at least one path between each pair of cities. If it is impossible to connect all the n
cities, return -1
,
The cost is the sum of the connections' costs used.
Example 1:
Input: n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]] Output: 6 Explanation: Choosing any 2 edges will connect all cities so we choose the minimum 2.
Example 2:
Input: n = 4, connections = [[1,2,3],[3,4,4]] Output: -1 Explanation: There is no way to connect all cities even if all edges are used. 其实union-find也没有那么难。一个union函数,一个find函数,哦了。 https://leetcode.com/problems/connecting-cities-with-minimum-cost/discuss/344867/Java-Kruskal's-Minimum-Spanning-Tree-Algorithm-with-Union-Find
class Solution { int[] parent; int n; private void union(int x, int y) { int px = find(x); int py = find(y); if (px != py) { parent[px] = py; n--; } } private int find(int x) { if (parent[x] == x) { return parent[x]; } parent[x] = find(parent[x]); // path compression return parent[x]; } public int minimumCost(int N, int[][] connections) { parent = new int[N + 1]; n = N; for (int i = 0; i <= N; i++) { parent[i] = i; } Arrays.sort(connections, (a, b) -> (a[2] - b[2])); int res = 0; for (int[] c : connections) { int x = c[0], y = c[1]; if (find(x) != find(y)) { res += c[2]; union(x, y); } } return n == 1 ? res : -1; } }
这篇关于1135. Connecting Cities With Minimum Cost 连接所有节点的最低价值的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23增量更新怎么做?-icode9专业技术文章分享
- 2024-11-23压缩包加密方案有哪些?-icode9专业技术文章分享
- 2024-11-23用shell怎么写一个开机时自动同步远程仓库的代码?-icode9专业技术文章分享
- 2024-11-23webman可以同步自己的仓库吗?-icode9专业技术文章分享
- 2024-11-23在 Webman 中怎么判断是否有某命令进程正在运行?-icode9专业技术文章分享
- 2024-11-23如何重置new Swiper?-icode9专业技术文章分享
- 2024-11-23oss直传有什么好处?-icode9专业技术文章分享
- 2024-11-23如何将oss直传封装成一个组件在其他页面调用时都可以使用?-icode9专业技术文章分享
- 2024-11-23怎么使用laravel 11在代码里获取路由列表?-icode9专业技术文章分享
- 2024-11-22怎么实现ansible playbook 备份代码中命名包含时间戳功能?-icode9专业技术文章分享