|
| 1 | +/** |
| 2 | + * @param {number[]} favorite |
| 3 | + * @return {number} |
| 4 | + */ |
| 5 | +var maximumInvitations = function(favorite) { |
| 6 | + const n = favorite.length, m = Array(n).fill(-1), r = Array.from({ length: n }, () => []) |
| 7 | + for(let i = 0; i < n; i++) r[favorite[i]].push(i) |
| 8 | + |
| 9 | + function dfs(u) { |
| 10 | + if(m[u] !== -1) return m[u] |
| 11 | + let res = 0 |
| 12 | + for(let v of r[u]) res = Math.max(res, dfs(v)) |
| 13 | + return m[u] = 1 + res |
| 14 | + } |
| 15 | + let res = 0, free = 0 |
| 16 | + for(let i = 0; i < n; ++i) { |
| 17 | + if (m[i] != -1) continue; // skip visited nodes |
| 18 | + if (favorite[favorite[i]] == i) { |
| 19 | + m[i] = m[favorite[i]] = 0; |
| 20 | + let a = 0, b = 0; // find the length of the longest arms starting from `i` and `A[i]` |
| 21 | + for (let v of r[i]) { |
| 22 | + if (v == favorite[i]) continue; |
| 23 | + a = Math.max(a, dfs(v)); |
| 24 | + } |
| 25 | + for (let v of r[favorite[i]]) { |
| 26 | + if (v == i) continue; |
| 27 | + b = Math.max(b, dfs(v)); |
| 28 | + } |
| 29 | + free += a + b + 2; // this free component is of length `a+b+2` |
| 30 | + } |
| 31 | + } |
| 32 | + function dfs2(u) { |
| 33 | + if (m[u] != -1) return[u, m[u], false]; // this is the merge point |
| 34 | + m[u] = 0; |
| 35 | + let [mergePoint, depth, mergePointMet] = dfs2(favorite[u]); |
| 36 | + if (mergePointMet) { // If we've met the merge point again already, this node is outside of the cycle and should be ignored. |
| 37 | + m[u] = 0; |
| 38 | + return [mergePoint, depth, true]; |
| 39 | + } |
| 40 | + m[u] = 1 + depth; // If we haven't met the merge point, we increment the depth. |
| 41 | + return [mergePoint, m[u], u == mergePoint]; |
| 42 | + } |
| 43 | + |
| 44 | + for(let i = 0; i < n; i++) { |
| 45 | + if(m[i] !== -1) continue |
| 46 | + let [mergePoint, depth, mergePointMet] = dfs2(i) |
| 47 | + if(mergePointMet) res = Math.max(res, depth) |
| 48 | + } |
| 49 | + |
| 50 | + return Math.max(res, free) |
| 51 | +}; |
| 52 | + |
0 commit comments