-
Notifications
You must be signed in to change notification settings - Fork 3
/
2127.cpp
55 lines (51 loc) · 1.55 KB
/
2127.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
class Solution {
public:
int maximumInvitations(vector<int>& favorite) {
int n = favorite.size();
vector<int> inDegrees(n, 0);
for (int i = 0; i < n; ++i) {
inDegrees[favorite[i]]++;
}
vector<bool> visited(n, false);
vector<int> depth(n, 1);
queue<int> q;
for (int i = 0; i < n; ++i) {
if (inDegrees[i] == 0) {
q.push(i);
visited[i] = true;
}
}
while (!q.empty()) {
int node = q.front();
q.pop();
int next = favorite[node];
inDegrees[next]--;
if (inDegrees[next] == 0) {
q.push(next);
visited[next] = true;
}
depth[next] = depth[node] + 1;
}
int maxSize = 0;
int twoNodeCircleSize = 0;
for (int i = 0; i < n; ++i) {
if (visited[i] == false) {
int cnt = 1;
int current = favorite[i];
visited[i] = true;
while (current != i) {
cnt++;
visited[current] = true;
current = favorite[current];
}
if (cnt >= 3) {
maxSize = max(maxSize, cnt);
}
else if (cnt == 2) {
twoNodeCircleSize += depth[i] + depth[favorite[i]];
}
}
}
return max(maxSize, twoNodeCircleSize);
}
};