File tree 1 file changed +63
-0
lines changed
1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n * (alpha(n) + r)) = O(n * r)
2
+ // Space: O(n)
3
+
4
+ class Solution {
5
+ public:
6
+ vector<bool > friendRequests (int n, vector<vector<int >>& restrictions, vector<vector<int >>& requests) {
7
+ vector<bool > result;
8
+ UnionFind uf (n);
9
+ for (const auto & request : requests) {
10
+ int pu = uf.find_set (request[0 ]), pv = uf.find_set (request[1 ]);
11
+ bool ok = true ;
12
+ for (const auto & restriction : restrictions) {
13
+ int px = uf.find_set (restriction[0 ]), py = uf.find_set (restriction[1 ]);
14
+ if ((px == pu && py == pv) || (px == pv && py == pu)) {
15
+ ok = false ;
16
+ break ;
17
+ }
18
+ }
19
+ result.emplace_back (ok);
20
+ if (ok) {
21
+ uf.union_set (request[0 ], request[1 ]);
22
+ }
23
+ }
24
+ return result;
25
+ }
26
+
27
+ private:
28
+ class UnionFind {
29
+ public:
30
+ UnionFind (const int n)
31
+ : set_(n)
32
+ , rank_(n) {
33
+ iota (set_.begin (), set_.end (), 0 );
34
+ }
35
+
36
+ int find_set (const int x) {
37
+ if (set_[x] != x) {
38
+ set_[x] = find_set (set_[x]); // Path compression.
39
+ }
40
+ return set_[x];
41
+ }
42
+
43
+ bool union_set (const int x, const int y) {
44
+ int x_root = find_set (x), y_root = find_set (y);
45
+ if (x_root == y_root) {
46
+ return false ;
47
+ }
48
+ if (rank_[x_root] < rank_[y_root]) { // Union by rank.
49
+ set_[x_root] = y_root;
50
+ } else if (rank_[x_root] > rank_[y_root]) {
51
+ set_[y_root] = x_root;
52
+ } else {
53
+ set_[y_root] = x_root;
54
+ ++rank_[x_root];
55
+ }
56
+ return true ;
57
+ }
58
+
59
+ private:
60
+ vector<int > set_;
61
+ vector<int > rank_;
62
+ };
63
+ };
You can’t perform that action at this time.
0 commit comments