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
use crate::algo::graph::UnweightedAdjacencyList;
#[derive(Debug, Eq, PartialEq)]
pub enum Center {
One(usize),
Two(usize, usize),
}
impl UnweightedAdjacencyList {
pub fn center(&self) -> Center {
let n = self.node_count();
let mut degrees = vec![0; n];
let mut leaves = Vec::new();
self.nodes().for_each(|(i, neighbours)| {
let degree = neighbours.len();
if degree <= 1 {
leaves.push(i);
}
degrees[i] = degree;
});
let mut processed_leaves = leaves.len();
while processed_leaves < n {
let mut new_leaves = Vec::new();
for &leaf in &leaves {
for &neighbour in &self[leaf] {
degrees[neighbour] = degrees[neighbour].saturating_sub(1);
if degrees[neighbour] == 1 {
new_leaves.push(neighbour);
}
}
}
processed_leaves += new_leaves.len();
leaves = new_leaves;
}
match leaves.len() {
1 => Center::One(leaves[0]),
2 => Center::Two(leaves[0], leaves[1]),
_ => unreachable!(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tree_center() {
let graph = UnweightedAdjacencyList::with_size(1);
assert_eq!(graph.center(), Center::One(0));
let mut graph = UnweightedAdjacencyList::with_size(2);
graph.add_undirected_edge(0, 1);
assert_eq!(graph.center(), Center::Two(0, 1));
let mut graph = UnweightedAdjacencyList::with_size(3);
graph.add_undirected_edge(0, 1);
graph.add_undirected_edge(1, 2);
assert_eq!(graph.center(), Center::One(1));
let mut graph = UnweightedAdjacencyList::with_size(9);
graph.add_undirected_edge(0, 1);
graph.add_undirected_edge(2, 1);
graph.add_undirected_edge(2, 3);
graph.add_undirected_edge(3, 4);
graph.add_undirected_edge(5, 3);
graph.add_undirected_edge(2, 6);
graph.add_undirected_edge(6, 7);
graph.add_undirected_edge(6, 8);
assert_eq!(graph.center(), Center::One(2));
}
}