algos/src/mwis.rs

60 lines
1.0 KiB
Rust
Raw Normal View History

2021-02-15 19:02:17 +01:00
#[derive(Debug)]
pub struct IndependentSet {
pub length: usize,
pub weights: Vec<u64>,
}
#[derive(Debug)]
struct Solution {
weight: u64,
nodes: Vec<usize>,
}
pub fn mwis(s: &IndependentSet) -> Vec<usize> {
let mut solutions: Vec<Solution> = Vec::new();
solutions.push(Solution {
weight: s.weights[0],
nodes: vec![0],
});
solutions.push(Solution {
weight: s.weights[1],
nodes: vec![1],
});
for i in 2..s.weights.len() {
let s1 = Solution {
weight: solutions[i - 1].weight,
nodes: solutions[i - 1].nodes.to_vec(),
};
let mut s2_vec = solutions[i - 2].nodes.to_vec();
s2_vec.push(i);
let s2 = Solution {
weight: solutions[i - 2].weight + s.weights[i],
nodes: s2_vec,
};
if s1.weight > s2.weight {
solutions.push(s1);
} else {
solutions.push(s2);
}
}
let solution = solutions.pop().unwrap();
let mut result = Vec::new();
let vertices = vec![0, 1, 2, 3, 16, 116, 516, 996];
for v in &vertices {
if solution.nodes.contains(v) {
result.push(1);
} else {
result.push(0);
}
}
result
}