import
java.util.*;
public
class
ModeOfAncestors {
private
static
Map<Integer, Integer> ans =
new
HashMap<>();
private
static
Map<Integer, Integer> freq =
new
HashMap<>();
private
static
TreeSet<Pair> s =
new
TreeSet<>(Comparator.comparing(Pair::getFrequency).thenComparing(Pair::getValue));
static
class
Pair {
int
value;
int
frequency;
public
Pair(
int
value,
int
frequency) {
this
.value = value;
this
.frequency = frequency;
}
public
int
getValue() {
return
value;
}
public
int
getFrequency() {
return
frequency;
}
}
private
static
void
addEdge(List<Integer>[] adj,
int
u,
int
v) {
adj[u].add(v);
adj[v].add(u);
}
private
static
void
helper(
int
v,
int
flag) {
if
(!freq.containsKey(v)) {
freq.put(v,
0
);
}
Pair pair =
new
Pair(v, freq.get(v));
s.remove(pair);
freq.put(v, freq.get(v) + flag);
s.add(
new
Pair(v, freq.get(v)));
}
private
static
void
modeOfAncestors(List<Integer>[] adj,
int
node,
int
[] vis, List<Integer> val) {
int
v = val.get(node);
helper(v,
1
);
ans.put(node, s.last().getValue());
vis[node] =
1
;
for
(
int
child : adj[node]) {
if
(vis[child] ==
0
) {
modeOfAncestors(adj, child, vis, val);
}
}
helper(v, -
1
);
}
public
static
void
main(String[] args) {
int
N =
9
;
List<Integer>[] adj =
new
ArrayList[N];
for
(
int
i =
0
; i < N; i++) {
adj[i] =
new
ArrayList<>();
}
addEdge(adj,
0
,
1
);
addEdge(adj,
0
,
2
);
addEdge(adj,
1
,
3
);
addEdge(adj,
1
,
4
);
addEdge(adj,
1
,
5
);
addEdge(adj,
2
,
6
);
addEdge(adj,
2
,
7
);
addEdge(adj,
2
,
8
);
List<Integer> val = Arrays.asList(
5
,
2
,
3
,
2
,
5
,
1
,
3
,
5
,
1
);
int
[] vis =
new
int
[N];
modeOfAncestors(adj,
0
, vis, val);
for
(
int
i =
0
; i < N; i++) {
System.out.print(ans.get(i) +
" "
);
}
System.out.println();
}
}