tipstar0125 / atcoder

atcoder
6 stars 0 forks source link

プリム法 #16

Open tipstar0125 opened 7 months ago

tipstar0125 commented 7 months ago

https://algo-logic.info/prim-mst/

tipstar0125 commented 7 months ago
tipstar0125 commented 7 months ago
input! {
    N: usize,
    M: usize,
    ABC: [(usize, usize, usize); M]
}

let mut G = vec![vec![]; N];
for &(a, b, c) in &ABC {
    G[a - 1].push((b - 1, c));
    G[b - 1].push((a - 1, c));
}

let mut used = vec![false; N];
let mut Q = BinaryHeap::new();
let mut ans = 0_usize;
used[0] = true;
for &(v, c) in &G[0] {
    Q.push((Reverse(c), v));
}
while let Some((Reverse(c), u)) = Q.pop() {
    if used[u] {
        continue;
    }
    used[u] = true;
    ans += c;
    for &(v, nc) in &G[u] {
        if !used[v] {
            Q.push((Reverse(nc), v));
        }
    }
}
println!("{}", ans);
tipstar0125 commented 7 months ago

ジャッジ:https://atcoder.jp/contests/tessoku-book/tasks/tessoku_book_bo 解答:https://atcoder.jp/contests/tessoku-book/submissions/47607753

tipstar0125 commented 7 months ago

計算量(V: 頂点、E: 辺)