結果

問題 No.1301 Strange Graph Shortest Path
ユーザー koba-e964koba-e964
提出日時 2020-12-08 03:14:37
言語 Rust
(1.77.0)
結果
AC  
実行時間 241 ms / 3,000 ms
コード長 6,030 bytes
コンパイル時間 2,145 ms
コンパイル使用メモリ 191,992 KB
実行使用メモリ 43,976 KB
最終ジャッジ日時 2023-10-17 16:53:47
合計ジャッジ時間 9,983 ms
ジャッジサーバーID
(参考情報)
judge15 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,348 KB
testcase_01 AC 1 ms
4,348 KB
testcase_02 AC 182 ms
41,752 KB
testcase_03 AC 157 ms
37,148 KB
testcase_04 AC 241 ms
40,396 KB
testcase_05 AC 161 ms
41,920 KB
testcase_06 AC 202 ms
37,288 KB
testcase_07 AC 195 ms
38,868 KB
testcase_08 AC 151 ms
37,636 KB
testcase_09 AC 199 ms
35,420 KB
testcase_10 AC 167 ms
37,060 KB
testcase_11 AC 219 ms
38,496 KB
testcase_12 AC 210 ms
38,488 KB
testcase_13 AC 182 ms
42,028 KB
testcase_14 AC 188 ms
35,336 KB
testcase_15 AC 186 ms
36,572 KB
testcase_16 AC 223 ms
40,388 KB
testcase_17 AC 202 ms
42,152 KB
testcase_18 AC 180 ms
38,240 KB
testcase_19 AC 206 ms
37,592 KB
testcase_20 AC 201 ms
36,604 KB
testcase_21 AC 200 ms
40,388 KB
testcase_22 AC 222 ms
37,676 KB
testcase_23 AC 197 ms
41,624 KB
testcase_24 AC 221 ms
37,280 KB
testcase_25 AC 233 ms
40,224 KB
testcase_26 AC 206 ms
38,500 KB
testcase_27 AC 211 ms
38,528 KB
testcase_28 AC 164 ms
41,380 KB
testcase_29 AC 232 ms
39,888 KB
testcase_30 AC 223 ms
40,016 KB
testcase_31 AC 231 ms
39,776 KB
testcase_32 AC 1 ms
4,348 KB
testcase_33 AC 115 ms
33,432 KB
testcase_34 AC 213 ms
43,976 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Write, BufWriter};
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes.by_ref().map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};
    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, [graph1; $len:expr]) => {{
        let mut g = vec![vec![]; $len];
        let ab = read_value!($next, [(usize1, usize1)]);
        for (a, b) in ab {
            g[a].push(b);
            g[b].push(a);
        }
        g
    }};
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };
    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };
    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };
    ($next:expr, usize1) => (read_value!($next, usize) - 1);
    ($next:expr, [ $t:tt ]) => {{
        let len = read_value!($next, usize);
        read_value!($next, [$t; len])
    }};
    ($next:expr, $t:ty) => ($next().parse::<$t>().expect("Parse error"));
}

#[allow(unused)]
macro_rules! debug {
    ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());
}
#[allow(unused)]
macro_rules! debugln {
    ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());
}

type Cap = isize;
type Cost = i64;
#[derive(Debug, Clone, Copy)]
struct Edge {
    to: usize,
    cap: Cap,
    cost: Cost,
    rev: usize, // rev is the position of reverse edge in graph[to]
}


#[derive(Debug, Clone)]
struct MinCostFlow {
    n: usize,
    graph: Vec<Vec<Edge>>,
    h: Vec<Cost>, // potential,
    dist: Vec<Cost>, // minimum distance
    prev: Vec<(usize, usize)>, // previous vertex and edge
}

impl MinCostFlow {
    // Initializes this solver. n is the number of vertices.
    fn new(n: usize) -> Self {
        MinCostFlow {
            n: n,
            graph: vec![vec![]; n],
            h: vec![0; n],
            dist: vec![0; n],
            prev: vec![(0, 0); n],
        }
    }
    fn add_edge(&mut self, from: usize, to: usize, cap: Cap, cost: Cost) {
        let fst = Edge {
            to: to,
            cap: cap,
            cost: cost,
            rev: self.graph[to].len(),
        };
        self.graph[from].push(fst);
        let snd = Edge {
            to: from,
            cap: 0,
            cost: -cost,
            rev: self.graph[from].len() - 1,
        };
        self.graph[to].push(snd);
    }
  // Calcucates the minimum cost flow whose source is s, sink is t, and flow is f.
    fn min_cost_flow(&mut self, s: usize, t: usize, mut f: Cap) -> Cost {
        let n = self.n;
        let inf: Cost = Cost::MAX / 2;
        let mut res = 0;
        for i in 0..n {
            self.h[i] = 0;
        }
        let h = &mut self.h;
        let dist = &mut self.dist;
        while f > 0 {
            let mut que = std::collections::BinaryHeap::<(Cost, usize)>::new();
            for i in 0..n {
                dist[i] = inf;
            }
            dist[s] = 0;
            que.push((0, s));
            while let Some((d, v)) = que.pop() {
                let d = -d;
                if dist[v] < d {
                    continue;
                }
                for (i, &e) in self.graph[v].iter().enumerate() {
                    if e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to] {
                        dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
                        self.prev[e.to] = (v, i);
                        que.push((-dist[e.to], e.to));
                    }
                }
            }
            if dist[t] == inf {
	        return -1; // Cannot add flow anymore
            }
            for i in 0..n {
                h[i] += dist[i];
            }
            // Add flow fully
            let mut d = f;
            let mut i = t;
            while i != s {
                let (pv, pe) = self.prev[i];
	        d = std::cmp::min(d, self.graph[pv][pe].cap);
                i = pv;
            }
            f -= d;
            res += d as Cost * h[t];
            i = t;
            while i != s {
                let (pv, pe) = self.prev[i];
                self.graph[pv][pe].cap -= d;
                let erev = self.graph[pv][pe].rev;
	        self.graph[i][erev].cap += d;
                i = pv;
            }
        }
        return res;
    }
}

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (let _ = write!(out,$($format)*););
    }
    #[allow(unused)]
    macro_rules! putvec {
        ($v:expr) => {
            for i in 0..$v.len() {
                puts!("{}{}", $v[i], if i + 1 == $v.len() {"\n"} else {" "});
            }
        }
    }
    input! {
        n: usize, m: usize,
        uvcd: [(usize1, usize1, i64, i64); m],
    }
    let mut flow = MinCostFlow::new(n);
    for &(u, v, c, d) in &uvcd {
        flow.add_edge(u, v, 1, c);
        flow.add_edge(u, v, 1, d);
        flow.add_edge(v, u, 1, c);
        flow.add_edge(v, u, 1, d);
    }
    let ans = flow.min_cost_flow(0, n - 1, 2isize);
    puts!("{}\n", ans);
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}
0