-
Notifications
You must be signed in to change notification settings - Fork 0
/
LonelyIsland.java
102 lines (90 loc) · 2.38 KB
/
LonelyIsland.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* https://www.hackerearth.com/practice/algorithms/graphs/topological-sort/practice-problems/algorithm/lonelyisland-49054110/
* #topological-sort
*/
/*
0 -> 1
0 -> 3
1 -> 2
2 -> 5
3 -> 4
5 -> 4
[0]
[1, 3]
[3, 2]
[2, 4]
[4, 5]
4
/ |
1 |
\ |
3* 1
/
2
*/
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;
class LonelyIsland {
public static void topoSort(
ArrayList<ArrayList<Integer>> graph, int[] inDegree, double[] probabilitiesArr) {
int sz = graph.size();
boolean[] visitedArr = new boolean[sz];
Deque<Integer> zeroInDegree = new LinkedList<>();
for (int i = 1; i < inDegree.length; i++) {
if (inDegree[i] == 0) {
zeroInDegree.addLast(i);
}
}
while (!zeroInDegree.isEmpty()) {
int node = zeroInDegree.pollFirst();
visitedArr[node] = true;
int div = graph.get(node).size();
for (int neighbour : graph.get(node)) {
if (!visitedArr[neighbour]) {
inDegree[neighbour] -= 1;
if (inDegree[neighbour] == 0) {
zeroInDegree.addLast(neighbour);
}
probabilitiesArr[neighbour] += probabilitiesArr[node] / div;
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int startNode = sc.nextInt();
int sz = n + 1;
double[] probabilitiesArr = new double[sz];
probabilitiesArr[startNode] = 1.0f;
ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
int[] inDegree = new int[sz];
for (int i = 0; i < sz; i++) {
graph.add(new ArrayList<>());
}
int u, v;
for (int i = 0; i < m; i++) {
u = sc.nextInt();
v = sc.nextInt();
graph.get(u).add(v);
inDegree[v] += 1;
}
topoSort(graph, inDegree, probabilitiesArr);
double maxProbility = Double.MIN_VALUE;
for (int i = 1; i < probabilitiesArr.length; i++) {
if (graph.get(i).isEmpty()) {
maxProbility = Math.max(maxProbility, probabilitiesArr[i]);
}
}
for (int idx = 1; idx < probabilitiesArr.length; idx++) {
if (maxProbility - probabilitiesArr[idx] <= 1e-9 && graph.get(idx).isEmpty()) {
System.out.print(idx + " ");
}
}
System.out.println();
return;
}
}