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
Explanation:
Choosing any 2 edges will connect all cities so we choose the minimum 2.
思路:Minimum spanning Tree;可以sort每条边,然后每次用最小的边connect,用union find做, T: O(nlogn), S: O(n)
class Solution {
public class UnionFind {
private int[] father;
private int size;
public UnionFind(int n) {
this.father = new int[n + 1];
for(int i = 0; i <= n; i++) {
father[i] = i;
}
this.size = n;
}
public int find(int x) {
int j = x;
// find root;
while(father[j] != j) {
j = father[j];
}
// path compression;
while(x != j) {
int fx = father[x];
father[x] = j;
x = fx;
}
return j;
}
public void union(int a, int b) {
int root_a = find(a);
int root_b = find(b);
if(root_a != root_b) {
father[root_a] = root_b;
this.size--;
}
}
public int getSize() {
return this.size;
}
}
public int minimumCost(int n, int[][] connections) {
Arrays.sort(connections, (a, b) ->(a[2] - b[2]));
UnionFind uf = new UnionFind(n);
int mincost = 0;
for(int[] connection: connections) {
int a = connection[0];
int b = connection[1];
int cost = connection[2];
if(uf.find(a) != uf.find(b)) {
uf.union(a, b);
mincost += cost;
}
}
return uf.getSize() == 1 ? mincost : -1;
}
}
思路2:这题也可以用dijkstra做,把cost的信息存入node里面,每次走向最小cost的node,然后收集visited node,最后走过的node的cost总和就是最小的cost;因为visited去掉更大的path了;注意:因为图是个无向图,所以一条边的两个node都要加;如果是两个点有多条边,也要加入,所以不能用hashmap,这里只能用list来构图;Time: O(ElogE) Space : O(E)
class Solution {
class Node {
public int id;
public int cost;
public Node(int id, int cost) {
this.id = id;
this.cost = cost;
}
}
public int minimumCost(int n, int[][] connections) {
HashMap<Integer, List<Node>> graph = new HashMap<>();
for(int[] connection: connections) {
int a = connection[0];
int b = connection[1];
int cost = connection[2];
graph.putIfAbsent(a, new ArrayList<Node>());
graph.putIfAbsent(b, new ArrayList<Node>());
graph.get(a).add(new Node(b, cost));
graph.get(b).add(new Node(a, cost));
}
int res = 0;
PriorityQueue<Node> pq = new PriorityQueue<Node>((a, b) -> (a.cost - b.cost));
pq.offer(new Node(1, 0));
HashSet<Integer> visited = new HashSet<>();
while(!pq.isEmpty()) {
Node node = pq.poll();
if(visited.contains(node.id)) {
continue;
}
visited.add(node.id);
res += node.cost;
for(Node neighbor: graph.get(node.id)) {
pq.offer(neighbor);
}
}
return visited.size() == n ? res : -1;
}
}