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 连接所有节点的最低价值的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-09CMS内容管理系统是什么?如何选择适合你的平台?
- 2025-01-08CCPM如何缩短项目周期并降低风险?
- 2025-01-08Omnivore 替代品 Readeck 安装与使用教程
- 2025-01-07Cursor 收费太贵?3分钟教你接入超低价 DeepSeek-V3,代码质量逼近 Claude 3.5
- 2025-01-06PingCAP 连续两年入选 Gartner 云数据库管理系统魔力象限“荣誉提及”
- 2025-01-05Easysearch 可搜索快照功能,看这篇就够了
- 2025-01-04BOT+EPC模式在基础设施项目中的应用与优势
- 2025-01-03用LangChain构建会检索和搜索的智能聊天机器人指南
- 2025-01-03图像文字理解,OCR、大模型还是多模态模型?PalliGema2在QLoRA技术上的微调与应用
- 2025-01-03混合搜索:用LanceDB实现语义和关键词结合的搜索技术(应用于实际项目)