Saturday, July 27, 2019

Leetcode 1135. Connecting Cities With Minimum Cost

https://leetcode.com/problems/connecting-cities-with-minimum-cost/description/

Description:

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.

Notes:

This question asks for the weights of the minimum spanning tree. There are very good resource online to this topic. For example,

https://www.geeksforgeeks.org/kruskals-minimum-spanning-tree-algorithm-greedy-algo-2/

The key algorithm involved is the so called union-find algorithm, which can be find in the below link,

https://www.geeksforgeeks.org/union-find/

See the code below:

  1. class Solution {
  2. public:
  3. int minimumCost(int N, vector<vector<int>>& conections) {
  4. sort(conections.begin(), conections.end(), [](auto &a, auto &b){return a[2] < b[2];});
  5. vector<int> ps(N+1, 0);
  6. for(int i=1; i<=N; ++i) ps[i] = i;
  7. int res = 0, ct = 1;
  8. for(auto &a : conections) {
  9. int x = find(a[0], ps), y = find(a[1], ps);
  10. if(x != y) {
  11. ps[x] = y;
  12. res += a[2];
  13. ++ct;
  14. if(ct==N) return res;
  15. }
  16. }
  17. return -1;
  18. }
  19. private:
  20. int find(int x, vector<int> &ps) {
  21. if(ps[x] != x) ps[x] = find(ps[x], ps);
  22. return ps[x];
  23. }
  24. };

No comments:

Post a Comment