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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
pub mod connectivity;
pub mod flow;
pub mod util;
pub struct DisjointSets {
parent: Vec<usize>,
}
impl DisjointSets {
pub fn new(size: usize) -> Self {
Self {
parent: (0..size).collect(),
}
}
pub fn find(&mut self, u: usize) -> usize {
let pu = self.parent[u];
if pu != u {
self.parent[u] = self.find(pu);
}
self.parent[u]
}
pub fn merge(&mut self, u: usize, v: usize) -> bool {
let (pu, pv) = (self.find(u), self.find(v));
self.parent[pu] = pv;
pu != pv
}
}
pub struct Graph {
first: Vec<Option<usize>>,
next: Vec<Option<usize>>,
endp: Vec<usize>,
}
impl Graph {
pub fn new(vmax: usize, emax_hint: usize) -> Self {
Self {
first: vec![None; vmax],
next: Vec::with_capacity(emax_hint),
endp: Vec::with_capacity(emax_hint),
}
}
pub fn num_v(&self) -> usize {
self.first.len()
}
pub fn num_e(&self) -> usize {
self.endp.len()
}
pub fn add_edge(&mut self, u: usize, v: usize) {
self.next.push(self.first[u]);
self.first[u] = Some(self.num_e());
self.endp.push(v);
}
pub fn add_undirected_edge(&mut self, u: usize, v: usize) {
self.add_edge(u, v);
self.add_edge(v, u);
}
pub fn add_two_sat_clause(&mut self, u: usize, v: usize) {
self.add_edge(u ^ 1, v);
self.add_edge(v ^ 1, u);
}
pub fn adj_list(&self, u: usize) -> AdjListIterator {
AdjListIterator {
graph: self,
next_e: self.first[u],
}
}
}
pub struct AdjListIterator<'a> {
graph: &'a Graph,
next_e: Option<usize>,
}
impl<'a> Iterator for AdjListIterator<'a> {
type Item = (usize, usize);
fn next(&mut self) -> Option<Self::Item> {
self.next_e.map(|e| {
let v = self.graph.endp[e];
self.next_e = self.graph.next[e];
(e, v)
})
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_adj_list() {
let mut graph = Graph::new(4, 4);
graph.add_edge(0, 1);
graph.add_edge(1, 2);
graph.add_edge(1, 3);
graph.add_edge(3, 0);
let adj: Vec<(usize, usize)> = graph.adj_list(1).collect();
assert_eq!(adj, vec![(2, 3), (1, 2)]);
}
}