|
| 1 | +class DistanceLimitedPathsExist { |
| 2 | + vector<pair<int,int>> snaps[10000]; |
| 3 | + int father[10000]; |
| 4 | + int rank[10000]; |
| 5 | + vector<int>dist; |
| 6 | + unordered_set<int>changed; |
| 7 | + int snapId = 0; |
| 8 | +public: |
| 9 | + DistanceLimitedPathsExist(int n, vector<vector<int>>& edgeList) |
| 10 | + { |
| 11 | + for (int i=0; i<n; i++) |
| 12 | + { |
| 13 | + snaps[i].push_back({-1, i}); |
| 14 | + father[i] = i; |
| 15 | + } |
| 16 | + |
| 17 | + sort(edgeList.begin(),edgeList.end(), [](auto const &a,auto const &b) { return a[2] < b[2]; }); |
| 18 | + |
| 19 | + int cur_dist = 0; |
| 20 | + for (auto e: edgeList) |
| 21 | + { |
| 22 | + if (e[2] > cur_dist) |
| 23 | + { |
| 24 | + dist.push_back(cur_dist); |
| 25 | + cur_dist = e[2]; |
| 26 | + for (auto node: changed) |
| 27 | + { |
| 28 | + snaps[node].push_back({snapId, father[node]}); |
| 29 | + } |
| 30 | + changed.clear(); |
| 31 | + snapId++; |
| 32 | + } |
| 33 | + int a = e[0], b = e[1]; |
| 34 | + Union(a,b); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + int findFather(int node) |
| 39 | + { |
| 40 | + while (father[node]!=node) |
| 41 | + node = father[node]; |
| 42 | + return node; |
| 43 | + } |
| 44 | + |
| 45 | + void Union(int a, int b) |
| 46 | + { |
| 47 | + a = findFather(a); |
| 48 | + b = findFather(b); |
| 49 | + if (findFather(a)!=findFather(b)) |
| 50 | + { |
| 51 | + if (rank[a]<rank[b]) |
| 52 | + { |
| 53 | + father[a] = b; |
| 54 | + rank[b] = max(rank[b], rank[a]+1); |
| 55 | + changed.insert(a); |
| 56 | + } |
| 57 | + else |
| 58 | + { |
| 59 | + father[b] = a; |
| 60 | + rank[a] = max(rank[a], rank[b]+1); |
| 61 | + changed.insert(b); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + int findSnapFather(int node, int snap_id) |
| 67 | + { |
| 68 | + auto iter = upper_bound(snaps[node].begin(), snaps[node].end(), make_pair(snap_id, INT_MAX)); |
| 69 | + iter = prev(iter,1); |
| 70 | + int f = iter->second; |
| 71 | + if (f==node) |
| 72 | + return f; |
| 73 | + else |
| 74 | + return findSnapFather(f, snap_id); |
| 75 | + } |
| 76 | + |
| 77 | + bool query(int p, int q, int limit) |
| 78 | + { |
| 79 | + int snap_id = lower_bound(dist.begin(), dist.end(), limit) - dist.begin() - 1; |
| 80 | + return findSnapFather(p, snap_id)==findSnapFather(q, snap_id); |
| 81 | + } |
| 82 | +}; |
| 83 | + |
| 84 | +/** |
| 85 | + * Your DistanceLimitedPathsExist object will be instantiated and called as such: |
| 86 | + * DistanceLimitedPathsExist* obj = new DistanceLimitedPathsExist(n, edgeList); |
| 87 | + * bool param_1 = obj->query(p,q,limit); |
| 88 | + */ |
0 commit comments