Advertisement
nikunjsoni

1584

Apr 29th, 2021
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     struct node{
  4.         int pt1, pt2, dist;
  5.        
  6.         bool operator()(node& a, node& b){
  7.             return a.dist > b.dist;
  8.         }
  9.     };
  10.    
  11.     class UnionFind{
  12.         vector<int> parent, rank;
  13.        
  14.         public:
  15.         int edges=0;
  16.         UnionFind(int n){
  17.             parent.resize(n);
  18.             rank.resize(n, 0);
  19.             for(int i=0; i<n; i++)
  20.                 parent[i]=i;
  21.         }
  22.        
  23.         int findParent(int x){
  24.             return (x == parent[x]) ? x : (parent[x] = findParent(parent[x]));
  25.         }
  26.        
  27.         bool Union(int x, int y){
  28.             int px = findParent(x);
  29.             int py = findParent(y);
  30.            
  31.             if(px == py) return false;
  32.            
  33.             if(rank[px] > rank[py]){
  34.                 parent[py] = px;
  35.             }
  36.             else{
  37.                 parent[px] = py;
  38.                 rank[py]++;
  39.             }
  40.             edges++;
  41.             return true;
  42.         }
  43.     };
  44.    
  45.     int minCostConnectPoints(vector<vector<int>>& points) {
  46.         priority_queue<node, vector<node>, node> pq;
  47.         int n=points.size();
  48.        
  49.         for(int i=0; i<n; i++){
  50.             for(int j=i+1; j<n; j++){
  51.                 int dist = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1]);
  52.                 pq.push({i, j, dist});
  53.             }
  54.         }
  55.        
  56.         int result=0;
  57.         UnionFind uf(n);
  58.        
  59.         while(!pq.empty()){
  60.             node curr = pq.top();
  61.             pq.pop();
  62.            
  63.             if(uf.Union(curr.pt1, curr.pt2))
  64.                 result += curr.dist;
  65.            
  66.             if(uf.edges == n-1) return result;
  67.         }
  68.         return 0;
  69.     }
  70. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement