跳转至

参加会议的最多员工数⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    int maximumInvitations(vector<int>& favorite) {
        int n = favorite.size();
        vector<int> inDegree(n);
        for (int f : favorite) {
            inDegree[f]++;
        }

        queue<int> que;
        for (int i = 0; i < n; i++) {
            if (inDegree[i] == 0) {
                que.push(i);
            }
        }

        vector<int> maxDepth(n);
        while (!que.empty()) {
            int current = que.front();
            que.pop();

            int next = favorite[current];
            maxDepth[next] = max(maxDepth[next], maxDepth[current] + 1);
            if (--inDegree[next] == 0) {
                que.push(next);
            }
        }

        int sumOfSpecialCircles = 0, regularCircle = 0;
        for (int i = 0; i < n; i++) {
            if (inDegree[i] > 0) {
                int circleSize = 1;
                inDegree[i] = 0;
                for (int x = favorite[i]; x != i; x = favorite[x]) {
                    circleSize++;
                    inDegree[x] = 0;
                }

                if (circleSize == 2) {
                    sumOfSpecialCircles += 2 + maxDepth[i] + maxDepth[favorite[i]];
                } else {
                    regularCircle = max(regularCircle, circleSize);
                }
            }
        }

        return max(sumOfSpecialCircles, regularCircle);
    }
};