-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution.cpp
64 lines (57 loc) · 1.5 KB
/
solution.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
56
57
58
59
60
61
62
63
64
class Solution
{
public:
int maximumInvitations(vector<int> &favorite)
{
int n = favorite.size();
vector<int> inDegree(n, 0), chainLengths(n, 0);
vector<bool> visited(n, false);
for (int fav : favorite)
{
inDegree[fav]++;
}
queue<int> q;
for (int i = 0; i < n; ++i)
{
if (inDegree[i] == 0)
{
q.push(i);
}
}
while (!q.empty())
{
int node = q.front();
q.pop();
visited[node] = true;
int next = favorite[node];
chainLengths[next] = chainLengths[node] + 1;
if (--inDegree[next] == 0)
{
q.push(next);
}
}
int maxCycle = 0, totalChains = 0;
for (int i = 0; i < n; ++i)
{
if (!visited[i])
{
int current = i, cycleLength = 0;
while (!visited[current])
{
visited[current] = true;
current = favorite[current];
cycleLength++;
}
if (cycleLength == 2)
{
totalChains += 2 + chainLengths[i] + chainLengths[favorite[i]];
}
else
{
maxCycle = max(maxCycle, cycleLength);
}
}
}
return max(maxCycle, totalChains);
}
};