Advertisement
theSwamz

MinCostToConnectNodes

Apr 16th, 2021
1,053
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 2.15 KB | None | 0 0
  1. // https://leetcode.com/discuss/interview-question/356981
  2. public class Main {
  3.     public static void main(String[] args) {
  4.         int n = 6;
  5.         int[][] edges = {{1, 4}, {4, 5}, {2, 3}};
  6.         int[][] newEdges = {{1, 2, 5}, {1, 3, 10}, {1, 6, 2}, {5, 6, 5}};
  7.         System.out.println(minCost(n, edges, newEdges));
  8.     }
  9.    
  10.     public static int minCost(int n, int[][] edges, int[][] newEdges) {
  11.         UF uf = new UF(n + 1); // + 1 because nodes are 1-based
  12.         for (int[] edge : edges) {
  13.             uf.union(edge[0], edge[1]);
  14.         }
  15.        
  16.         Queue<int[]> pq = new PriorityQueue<>(newEdges.length, (e1, e2) -> Integer.compare(e1[2], e2[2]));
  17.         pq.addAll(Arrays.asList(newEdges));
  18.        
  19.         int totalCost = 0;
  20.         // 2 because nodes are 1-based and we have 1 unused component at index 0
  21.         while (!pq.isEmpty() && uf.count != 2) {
  22.             int[] edge = pq.poll();
  23.             if (!uf.connected(edge[0], edge[1])) {
  24.                 uf.union(edge[0], edge[1]);
  25.                 totalCost += edge[2];
  26.             }
  27.         }
  28.         return totalCost;
  29.     }
  30. }
  31.  
  32. class UF {
  33.     private int[] parent;  // parent[i] = parent of i
  34.     private byte[] rank;   // rank[i] = rank of subtree rooted at i (never more than 31)
  35.     public int count;      // number of connected components
  36.  
  37.     public UF(int n) {
  38.         if (n < 0) throw new IllegalArgumentException();
  39.         parent = new int[n];
  40.         rank = new byte[n];
  41.         for (int i = 0; i < n; i++) {
  42.             parent[i] = i;
  43.         }
  44.         count = n;
  45.     }
  46.  
  47.     public int find(int p) {
  48.         while (p != parent[p]) {
  49.             parent[p] = parent[parent[p]];
  50.             p = parent[p];
  51.         }
  52.         return p;
  53.     }
  54.  
  55.     public void union(int p, int q) {
  56.         int pr = find(p);
  57.         int qr = find(q);
  58.         if (pr == qr) return;
  59.         if (rank[pr] < rank[qr]) {
  60.             parent[pr] = qr;
  61.         } else {
  62.             parent[qr] = pr;
  63.             if (rank[pr] == rank[qr]) rank[pr]++;
  64.         }
  65.         count--;
  66.     }
  67.  
  68.     public boolean connected(int p, int q) {
  69.         return find(p) == find(q);
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement