graph_algo_ptas/algorithm/dynamic_programming/
utils.rs

1use arboretum_td::graph::{BaseGraph, HashMapGraph, MutableGraph};
2use bitvec::vec::BitVec;
3use fxhash::FxHashSet;
4use itertools::Itertools;
5use std::collections::HashMap;
6
7pub fn bit_vec_powerset(set: &FxHashSet<usize>, subset_size: usize) -> Vec<BitVec> {
8    set.iter()
9        .powerset()
10        .map(|subset| to_bit_vec(subset.iter().copied(), subset_size))
11        .collect()
12}
13
14pub fn init_bit_vec(size: usize) -> BitVec {
15    let n = (size as f64 / 64.0).ceil() as usize;
16
17    BitVec::from_vec(vec![0; n])
18}
19
20pub fn to_bit_vec<'a>(it: impl Iterator<Item = &'a usize>, size: usize) -> BitVec {
21    let mut bit_vec: BitVec = init_bit_vec(size);
22
23    for x in it {
24        bit_vec.set(*x, true);
25    }
26
27    bit_vec
28}
29
30pub fn immutable_bit_vec_update(subset: &BitVec, v: usize) -> BitVec {
31    let mut subset = subset.clone();
32    subset.set(v, true);
33    subset
34}
35
36// the result is a graph isomorphic to the input graph but is guaranteed to have vertex IDs 0..n-1.
37pub fn remap_vertices(graph: &HashMapGraph) -> (HashMapGraph, HashMap<usize, usize>) {
38    let mut remapped_graph = HashMapGraph::new();
39    let mut forward_mapping = HashMap::new();
40    let mut backward_mapping = HashMap::new();
41
42    for (i, v) in graph.vertices().enumerate() {
43        remapped_graph.add_vertex(i);
44        forward_mapping.insert(v, i);
45        backward_mapping.insert(i, v);
46    }
47
48    for u in graph.vertices() {
49        for v in graph.neighborhood(u) {
50            let remapped_u = forward_mapping.get(&u).unwrap();
51            let remapped_v = forward_mapping.get(&v).unwrap();
52            remapped_graph.add_edge(*remapped_u, *remapped_v);
53        }
54    }
55
56    (remapped_graph, backward_mapping)
57}