Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Single Source Shortest Path II

For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$.

Input

In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format:

$u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$

Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$).

Output

For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs.

Constraints

$1 \leq n \leq 10,000$

$0 \leq c_i \leq 100,000$

$|E| < 500,000$

All vertices are reachable from vertex $0$

Sample Input 1

5
0 3 2 3 3 1 1 2
1 2 0 2 3 4
2 3 0 3 3 1 4 1
3 4 2 1 0 1 1 4 4 3
4 2 2 1 3 3

Sample Output 1

0 0
1 2
2 2
3 1
4 3

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.

Solution in Rust (judge verdict: Accepted)

#![allow(dead_code)]
use std::io::{self, Read};
use std::str::FromStr;
use std::u64;
use std::collections::VecDeque;
use std::collections::BinaryHeap;

pub struct Scanner<R: Read> {
    reader: R,
}
impl<R: Read> Scanner<R> {
    pub fn new(reader: R) -> Scanner<R> {
        Scanner { reader: reader }
    }
    pub fn read<T: FromStr>(&mut self) -> T {
        let s = self
            .reader
            .by_ref()
            .bytes()
            .map(|c| c.expect("failed to read char") as char)
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect::<String>();
        s.parse::<T>().ok().expect("failed to parse token")
    }
}

// 通常のキューを使った探索。これでも時間内で動作した
fn solve(mat: &Vec<Vec<(usize, u64)>>) -> Vec<u64> {
    let n = mat.len();
    let mut dist = vec![u64::MAX; n];
    dist[0] = 0;

    let mut que = VecDeque::new();
    que.push_back(0);

    while let Some(idx) = que.pop_front() {
        for &(i, d) in mat[idx].iter() {
            let s = dist[idx] + d;
            if s < dist[i] {
                dist[i] = s;
                que.push_back(i);
            }
        }
    }

    dist
}

// BinaryHeapで用いるためのStruct
#[derive(Eq, PartialEq)]
struct Node {
    idx: usize,
    cost: u64,
}

impl Ord for Node {
    fn cmp(&self, other :&Node) -> std::cmp::Ordering {
        // Minヒープにするため、比較を左右逆にする(cost小さい、idx小さい)
        // まず、左右逆のcostの比較を行う
        other.cost.cmp(&self.cost)
            // コストが同じだった場合(thenはEqual時のみ呼び出しで、それ以外はそのまま値を返す)、
            // 左右逆のidxの比較を行う
            .then_with(|| self.idx.cmp(&other.idx))
    }
}

// PartialOrdも順序比較に実装が必要。ここではNanは存在しないのでOrdの実装をSomeでラップするだけ
impl PartialOrd for Node {
    fn partial_cmp(&self, other: &Node) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}


// 二分ヒープを用いたダイクストラ法
fn solve_binary_heap(mat: &Vec<Vec<(usize, u64)>>) -> Vec<u64> {
    let n = mat.len();
    let mut dist = vec![u64::MAX; n];
    let mut par = vec![None; n];    // 親

    dist[0] = 0;
    let mut heap = BinaryHeap::new();
    heap.push(Node {idx: 0, cost: 0,});

    while let Some(Node{idx, cost: _cost}) = heap.pop() {
        for &(i, d) in mat[idx].iter() {
            let s = dist[idx] + d;
            if s < dist[i] {
                dist[i] = s;
                par[i] = Some(idx);
                heap.push(Node {idx: i, cost: dist[i], });
            }
        }
    }

    dist
}


fn main() {
    let sin = io::stdin();
    let sin = sin.lock();
    let mut sc = Scanner::new(sin);

    let n: usize = sc.read();

    let mut mat: Vec<Vec<(usize, u64)>> = vec![vec![]; n];
    for _ in 0..n {
        let u: usize = sc.read();
        let k: usize = sc.read();
        for _ in 0..k {
            let v: usize = sc.read();
            let c: u64 = sc.read();
            mat[u].push((v, c));
        }
    }

    // let dist = solve(&mat);
    let dist = solve_binary_heap(&mat);

    for i in 0..n {
        println!("{} {}", i, dist[i]);
    }
}