forked from sherxon/AlgoDS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenealogicalTree.java
More file actions
104 lines (88 loc) · 2.63 KB
/
GenealogicalTree.java
File metadata and controls
104 lines (88 loc) · 2.63 KB
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
103
104
package timus;
import java.util.*;
/**
* Created by sherxon on 2016-11-26.
*/
public class GenealogicalTree {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
int n=in.nextInt();
G g= new G();
Set<Integer> roots= new TreeSet<>((a, b)->b.compareTo(a));
for (int i = 1; i <=n; i++) {
g.addVertex(i);
roots.add(i);
}
int child=-1;
for (int i = 1; i <=n;) {
child=in.nextInt();
if(child==0){
i++;
}else{
roots.remove(Integer.valueOf(child));
g.addEdge(i,child, 0);
}
}
g.reset();
Stack<Integer> stack= new Stack<>();
for (Integer root : roots) {
topSort(g, root, stack);
}
while (!stack.empty())
System.out.print(stack.pop() + " ");
System.out.println();
}
public static void topSort(G graph, Integer start, Stack<Integer> list){
G.V vertex=graph.vertices.get(start);
vertex.visited=true;
if(vertex.edges.size()>0){
for (G.E edge : vertex.edges) {
if(!edge.to.visited) {
topSort(graph, edge.to.label, list);
}
}
}
list.add(vertex.label);
}
private static class G{
private Map<Integer, V> vertices= new LinkedHashMap<>();
public void addVertex(Integer v){
V newV= new V(v);
vertices.putIfAbsent(v, newV);
}
public void addEdge(Integer from, Integer to, int weight){
V fromV=vertices.get(from);
V toV=vertices.get(to);
E e= new E(fromV, toV, weight);
fromV.edges.add(e); // directed graph
}
public void reset() {
vertices.values().stream().forEach(s->s.visited=false);
}
public class V implements Comparable{
List<E> edges= new ArrayList<>();
private Integer label;
int distance;
V parent;
boolean visited;
public V(Integer label) {
this.label = label;
this.distance=0;
}
@Override
public int compareTo(Object o) {
return this.distance - ((V)o).distance;
}
}
private class E{
V from;
V to;
int weight;
public E(V from, V to, int weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
}
}
}