-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathTeads.java
81 lines (63 loc) · 2.54 KB
/
Teads.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
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.stream.Collectors;
// https://www.codingame.com/training/medium/teads-sponsored-contest
class Solution {
private static class Node {
private final Integer id;
private final Set<Node> adjacentNodes;
private Node(Integer id) {
this.id = id;
this.adjacentNodes = new HashSet<>();
}
public Integer getId() {
return id;
}
public void addAdjacentNode(Node adjacentNodeId) {
adjacentNodes.add(adjacentNodeId);
}
public void removeAdjacentNode(Node adjacentNodeId) {
adjacentNodes.remove(adjacentNodeId);
}
public void removeFromAdjacentNodes() {
adjacentNodes.stream().forEach(adjacentNode -> adjacentNode.removeAdjacentNode(this));
}
public boolean isLeaf() {
return adjacentNodes.size() == 1;
}
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(); // the number of adjacency relations
Map<Integer, Node> graph = new HashMap<>();
for (int i = 0; i < n; i++) {
Integer xi = Integer.valueOf(in.nextInt()); // the ID of a person which is adjacent to yi
Integer yi = Integer.valueOf(in.nextInt()); // the ID of a person which is adjacent to xi
Node xiNode = graph.computeIfAbsent(xi, key -> new Node(key));
Node yiNode = graph.computeIfAbsent(yi, key -> new Node(key));
xiNode.addAdjacentNode(yiNode);
yiNode.addAdjacentNode(xiNode);
}
System.out.println(calculateMinimumPropagationSteps(graph)); // The minimal amount of steps required to completely propagate the advertisement
}
private static int calculateMinimumPropagationSteps(Map<Integer, Node> graph) {
int minimumPropagationSteps = 0;
while (graph.size() > 1) {
removeLeaves(graph);
minimumPropagationSteps++;
}
return minimumPropagationSteps;
}
private static void removeLeaves(Map<Integer, Node> graph) {
//use filter on stream to put in set
Set<Node> leaves = graph.values().stream().filter(Node::isLeaf).collect(Collectors.toSet());
//use lambda definitions to remove leaves
leaves.stream().forEach(leaf -> {
graph.remove(leaf.getId());
leaf.removeFromAdjacentNodes();
});
}
}