forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-employees-to-be-invited-to-a-meeting.cpp
59 lines (56 loc) · 1.66 KB
/
maximum-employees-to-be-invited-to-a-meeting.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
58
59
// Time: O(n)
// Space: O(n)
class Solution {
public:
int maximumInvitations(vector<int>& favorite) {
vector<vector<int>> inv_adj(size(favorite));
for (int u = 0; u < size(favorite); ++u) {
inv_adj[favorite[u]].emplace_back(u);
}
int result = 0, cycle_2s = 0;
for (const auto& [u, l] : find_cycles(favorite)) {
if (l > 2) {
result = max(result, l);
continue;
}
cycle_2s += bfs(inv_adj, u, favorite[u]) + bfs(inv_adj, favorite[u], u);
}
return max(result, cycle_2s);
}
private:
vector<pair<int, int>> find_cycles(const vector<int>& adj) {
vector<pair<int, int>> result;
vector<bool> lookup(size(adj));
for (int i = 0; i < size(adj); ++i) {
unordered_map<int, int> cnt;
int u = i;
while (!lookup[u]) {
lookup[u] = true;
cnt[u] = size(cnt);
u = adj[u];
}
if (cnt.count(u)) {
result.emplace_back(u, size(cnt) - cnt[u]);
}
}
return result;
}
int bfs(const vector<vector<int>>& adj, int u, int exclude) {
int result = 0;
vector<int> q = {u};
while (!empty(q)) {
++result;
vector<int> new_q;
for (const auto& u : q) {
for (const auto& v : adj[u]) {
if (v == exclude) {
continue;
}
new_q.emplace_back(v);
}
}
q = move(new_q);
}
return result;
}
};