-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2127.java
55 lines (53 loc) · 1.49 KB
/
2127.java
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
return Math.max(maxCycle(favorite), topologicalSort(favorite));
}
private int maxCycle(int[] fa) {
int n = fa.length;
boolean[] vis = new boolean[n];
int ans = 0;
for (int i = 0; i < n; ++i) {
if (vis[i]) {
continue;
}
List<Integer> cycle = new ArrayList<>();
int j = i;
while (!vis[j]) {
cycle.add(j);
vis[j] = true;
j = fa[j];
}
for (int k = 0; k < cycle.size(); ++k) {
if (cycle.get(k) == j) {
ans = Math.max(ans, cycle.size() - k);
}
}
}
return ans;
}
private int topologicalSort(int[] fa) {
int n = fa.length;
int[] indeg = new int[n];
int[] dist = new int[n];
Arrays.fill(dist, 1);
for (int v : fa) {
indeg[v]++;
}
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n; ++i) {
if (indeg[i] == 0) {
q.offer(i);
}
}
int ans = 0;
while (!q.isEmpty()) {
int i = q.pollFirst();
dist[fa[i]] = Math.max(dist[fa[i]], dist[i] + 1);
if (--indeg[fa[i]] == 0) {
q.offer(fa[i]);
}
}
for (int i = 0; i < n; ++i) {
if (i == fa[fa[i]]) {
ans += dist[i];
}
}
return ans;