File tree 1 file changed +48
-0
lines changed
1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int maximumInvitations(vector<int>& favorite) {
4
+
5
+ int n = favorite.size();
6
+ vector<int> indegree(n, 0);
7
+ vector<int> chain(n, 0);
8
+ vector<bool> vis(n, false);
9
+ for (int i : favorite) {
10
+ indegree[i]++;
11
+ }
12
+ queue<int> q;
13
+ for (int i = 0; i < n; i++) {
14
+ if (!indegree[i]) {
15
+ q.push(i);
16
+ }
17
+ }
18
+ while (!q.empty()) {
19
+ int front = q.front();
20
+ q.pop();
21
+ vis[front] = true;
22
+ int next = favorite[front];
23
+ chain[next] = chain[front] + 1;
24
+ if (--indegree[next] == 0) {
25
+ q.push(next);
26
+ }
27
+ }
28
+
29
+ int maxCycle = 0, total = 0;
30
+ for (int i = 0; i < n; i++) {
31
+ if (!vis[i]) {
32
+ int c = i, len = 0;
33
+ while (!vis[c]) {
34
+ vis[c] = true;
35
+ c = favorite[c];
36
+ len++;
37
+ }
38
+ if (len == 2) {
39
+ total += (2 + chain[i] + chain[favorite[i]]);
40
+ } else {
41
+ maxCycle = max(maxCycle, len);
42
+ }
43
+ }
44
+ }
45
+ return max(total, maxCycle);
46
+
47
+ }
48
+ };
You can’t perform that action at this time.
0 commit comments