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 thencities 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:
1 2 3
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:
1 2 3
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.
int sum = 0; for (auto connection : connections) { int p = connection[0]; int q = connection[1]; int findP = find(p); int findQ = find(q); if (findP == findQ) { continue; } else { parent[findP] = findQ; sum += connection[2]; count--; } }
intminimumCost(int n, vector<vector<int>>& connections){ int count = n; graph = vector<vector<vector<int>>>(n + 1, vector<vector<int>>()); visited = vector<bool>(n + 1, false);
for (auto connection : connections) { int p = connection[0]; int q = connection[1]; int w = connection[2]; graph[p].push_back({w, q}); graph[q].push_back({w, p}); }
int cost = 0; visited[1] = true; cut(1); while (!pq.empty()) { vector<int> pair = pq.top(); pq.pop(); int node = pair[1]; if (visited[node]) { continue; } n--; int w = pair[0]; visited[node] = true; cost += w; cut(node); }
return n == 1 ? cost : -1; }
voidcut(int node){ for (auto edge : graph[node]) { int to = edge[1]; if (visited[to]) { continue; } else { int w = edge[0]; pq.push({w, to}); } } } };