library-rs

This documentation is automatically generated by competitive-verifier/competitive-verifier

View the Project on GitHub naoya675/library-rs

:warning: graph/warshall-floyd/src/struct.rs

Code

#[derive(Debug, Clone, Copy)]
pub struct Edge {
    from: usize,
    to: usize,
    cost: i64,
}

impl Edge {
    pub fn new(from: usize, to: usize, cost: i64) -> Self {
        Self { from, to, cost }
    }
}

#[derive(Debug, Clone)]
pub struct WarshallFloyd {
    size: usize,
    edge: Vec<Edge>,
}

impl WarshallFloyd {
    pub fn new(size: usize) -> Self {
        Self { size, edge: vec![] }
    }

    pub fn add_edge(&mut self, from: usize, to: usize, cost: i64) {
        self.edge.push(Edge::new(from, to, cost));
    }

    pub fn warshall_floyd(&mut self) -> (bool, Vec<Vec<i64>>) {
        let mut dist = vec![vec![i64::MAX / 4; self.size]; self.size];
        for i in 0..self.size {
            dist[i][i] = 0;
        }
        for edge in &self.edge {
            dist[edge.from][edge.to] = edge.cost;
        }
        for k in 0..self.size {
            for i in 0..self.size {
                for j in 0..self.size {
                    dist[i][j] = dist[i][j].min(dist[i][k] + dist[k][j])
                }
            }
        }
        for i in 0..self.size {
            if dist[i][i] < 0 {
                return (true, dist);
            }
        }
        (false, dist)
    }
}
Back to top page