Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class UnionFind{
- vector<int> p, rank;
- public:
- UnionFind(int n){
- p.resize(n);
- rank.resize(n, 0);
- for(int i=0; i<n; i++)
- p[i] = i;
- }
- int findParent(int x){
- return (x == p[x]) ? x : (p[x] = findParent(p[x]));
- }
- void unionSet(int x, int y){
- int px = findParent(x);
- int py = findParent(y);
- if(px != py){
- if(rank[px] > rank[py]){
- p[py] = px;
- }
- else{
- p[px] = py;
- rank[py]++;
- }
- }
- }
- };
- class Solution {
- public:
- vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList, vector<vector<int>>& queries) {
- UnionFind uf = UnionFind(n);
- // Add index to query.
- for(int i=0; i<queries.size(); i++)
- queries[i].push_back(i);
- // Sort queries and edges.
- sort(queries.begin(), queries.end(), [](auto &a, auto &b) { return a[2] < b[2];});
- sort(edgeList.begin(), edgeList.end(), [](auto &a, auto &b) { return a.back() < b.back();});
- vector<bool> ans(queries.size(), false);
- int i = 0, j = 0;
- while(i<queries.size()){
- // Add edges with cost less than top query.
- while(j< edgeList.size() && edgeList[j][2] < queries[i][2]){
- uf.unionSet(edgeList[j][0], edgeList[j][1]);
- j++;
- }
- // Find parents of query points, if in same set, sset answer to true for it.
- int px = uf.findParent(queries[i][0]);
- int py = uf.findParent(queries[i][1]);
- if(px == py)
- ans[queries[i][3]] = true;
- i++;
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement