Advertisement
nikunjsoni

1697

Apr 29th, 2021
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. class UnionFind{
  2.     vector<int> p, rank;
  3.    
  4.     public:
  5.     UnionFind(int n){
  6.         p.resize(n);
  7.         rank.resize(n, 0);
  8.         for(int i=0; i<n; i++)
  9.             p[i] = i;
  10.     }  
  11.    
  12.     int findParent(int x){
  13.         return (x == p[x]) ? x : (p[x] = findParent(p[x]));
  14.     }
  15.    
  16.     void unionSet(int x, int y){
  17.         int px = findParent(x);
  18.         int py = findParent(y);
  19.         if(px != py){
  20.             if(rank[px] > rank[py]){
  21.                 p[py] = px;
  22.             }
  23.             else{
  24.                 p[px] = py;
  25.                 rank[py]++;
  26.             }
  27.         }
  28.     }
  29.    
  30. };
  31.  
  32. class Solution {
  33. public:
  34.     vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList, vector<vector<int>>& queries) {
  35.         UnionFind uf = UnionFind(n);
  36.        
  37.         // Add index to query.
  38.         for(int i=0; i<queries.size(); i++)
  39.             queries[i].push_back(i);
  40.        
  41.         // Sort queries and edges.
  42.         sort(queries.begin(), queries.end(), [](auto &a, auto &b) { return a[2] < b[2];});
  43.         sort(edgeList.begin(), edgeList.end(), [](auto &a, auto &b) { return a.back() < b.back();});
  44.        
  45.         vector<bool> ans(queries.size(), false);
  46.         int i = 0, j = 0;
  47.         while(i<queries.size()){
  48.             // Add edges with cost less than top query.
  49.             while(j< edgeList.size() && edgeList[j][2] < queries[i][2]){
  50.                 uf.unionSet(edgeList[j][0], edgeList[j][1]);
  51.                 j++;
  52.             }
  53.            
  54.             // Find parents of query points, if in same set, sset answer to true for it.
  55.             int px = uf.findParent(queries[i][0]);
  56.             int py = uf.findParent(queries[i][1]);
  57.             if(px == py)
  58.                 ans[queries[i][3]] = true;
  59.             i++;
  60.         }
  61.         return ans;
  62.     }
  63. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement