-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2127_Maximum_Employees_to_Be_Invited_to_a_Meeting.js
59 lines (57 loc) · 1.3 KB
/
2127_Maximum_Employees_to_Be_Invited_to_a_Meeting.js
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
/**
* @param {number[]} favorite
* @return {number}
*/
var maximumInvitations = function(favorite) {
return Math.max(maxCycle(favorite), topologicalSort(favorite));
};
function maxCycle(fa) {
const n = fa.length;
const vis = Array(n).fill(false);
let ans = 0;
for (let i = 0; i < n; ++i) {
if (vis[i]) {
continue;
}
const cycle = [];
let j = i;
for (; !vis[j]; j = fa[j]) {
cycle.push(j);
vis[j] = true;
}
for (let k = 0; k < cycle.length; ++k) {
if (cycle[k] === j) {
ans = Math.max(ans, cycle.length - k);
}
}
}
return ans;
}
function topologicalSort(fa) {
const n = fa.length;
const indeg = Array(n).fill(0);
const dist = Array(n).fill(1);
for (const v of fa) {
++indeg[v];
}
const q = [];
for (let i = 0; i < n; ++i) {
if (indeg[i] === 0) {
q.push(i);
}
}
let ans = 0;
while (q.length) {
const i = q.pop();
dist[fa[i]] = Math.max(dist[fa[i]], dist[i] + 1);
if (--indeg[fa[i]] === 0) {
q.push(fa[i]);
}
}
for (let i = 0; i < n; ++i) {
if (i === fa[fa[i]]) {
ans += dist[i];
}
}
return ans;
}