-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChecking Existence of Edge Length Limited Paths.cpp
57 lines (49 loc) · 1.39 KB
/
Checking Existence of Edge Length Limited Paths.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class UnionFind {
public:
UnionFind(int n) : id(n), rank(n) {
iota(begin(id), end(id), 0);
}
void unionByRank(int u, int v) {
const int i = find(u);
const int j = find(v);
if (i == j)
return;
if (rank[i] < rank[j]) {
id[i] = id[j];
} else if (rank[i] > rank[j]) {
id[j] = id[i];
} else {
id[i] = id[j];
++rank[j];
}
}
int find(int u) {
return id[u] == u ? u : id[u] = find(id[u]);
}
private:
vector<int> id;
vector<int> rank;
};
class Solution {
public:
vector<bool> distanceLimitedPathsExist(int n, vector<vector<int>>& edgeList,
vector<vector<int>>& queries) {
vector<bool> ans(queries.size());
UnionFind uf(n);
for (int i = 0; i < queries.size(); ++i)
queries[i].push_back(i);
sort(begin(queries), end(queries),
[](const auto& a, const auto& b) { return a[2] < b[2]; });
sort(begin(edgeList), end(edgeList),
[](const auto& a, const auto& b) { return a[2] < b[2]; });
int i = 0; // i := edgeList's index
for (const vector<int>& query : queries) {
// Union edges whose distances < limit (query[2])
while (i < edgeList.size() && edgeList[i][2] < query[2])
uf.unionByRank(edgeList[i][0], edgeList[i++][1]);
if (uf.find(query[0]) == uf.find(query[1]))
ans[q.back()] = true;
}
return ans;
}
};