Go: // ダイクストラのアルゴリズム
package main

import (
	"bufio"
	"fmt"
	"log"
	"math"
	"os"
	"strconv"
	"strings"
)

type color int

const (
	white color = iota // 未訪問
	mst                // MSTとして確定
)

// 頂点
type node struct {
	num     int         // 頂点の番号
	weights map[int]int // 重みMAP
	parent  *node       // MSTへの重み最小の親
	sum     int         // 始点からの距離
	color   color
}

func (p *node) getMinToMst() int {
	if p.parent == nil {
		return math.MaxInt32
	}
	return p.weights[p.parent.num]
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	n := eGetInt(scanner)

	nodes := make([]*node, n)
	for i := 0; i < n; i++ {
		weights := eAtoi((strings.Fields(eGetline(scanner))))
		v := &node{weights[0], make(map[int]int, weights[1]), nil, 0, white}
		for j := 0; j < weights[1]; j++ {
			k := weights[j*2+2] // 相手の頂点名
			w := weights[j*2+3] // 重み
			v.weights[k] = w
		}
		nodes[i] = v
	}

	// 初回はnode[0]がMSTに入るように
	nodes[0].parent = nodes[0]

	for { // 全部チェックするまで

		// どの頂点を新たにMSTに取り込むか

		var minNode *node
		min := math.MaxInt32
		for _, v := range nodes {
			if v.color == mst {
				continue
			}
			if v.getMinToMst() < min {
				min = v.getMinToMst()
				minNode = v
			}
		}
		if minNode == nil {
			// すべて完了している.
			break
		}

		// MSTに追加する頂点決定
		minNode.color = mst
		// 自分の親の合計値と合算する
		minNode.sum = minNode.parent.sum + min

		// MSTに属していない頂点それぞれについて,MSTとの最小の重みの距離を加算
		for _, v := range nodes {
			if v.color == mst {
				continue
			}
			w, ok := v.weights[minNode.num]
			if !ok {
				// minNodeと接してない
				continue
			}

			if w < v.getMinToMst() {
				// minNodeへの距離がもっとも重みが少ないので親を変更
				v.parent = minNode
			}
		}
	}

	for i, v := range nodes {
		fmt.Printf("%d %d\n", i, v.sum)
	}
}

func eGetInt(scanner *bufio.Scanner) int {
	t := eAtoi(strings.Fields(eGetline(scanner)))
	return t[0]
}

func eGetline(p *bufio.Scanner) string {
	if !p.Scan() {
		if err := p.Err(); err != nil {
			log.Fatal(err.Error())
		}
		return ""
	}
	return p.Text()
}

func eAtoi(s []string) []int {
	ints := make([]int, len(s))
	var err error
	for i, e := range s {
		ints[i], err = strconv.Atoi(e)
		if err != nil {
			log.Fatal(err.Error())
		}
	}
	return ints
}

Python: import sys
input = sys.stdin.readline


# import heapq
import heapq

# graph: 隣接リスト (頂点、距離）の順に格納
# start: 始点 (0-index)
# n: 頂点数
# memo[t]: startからtまでの最短距離
# return memo

def dijkstra(graph, start, n):
    INF = float('inf')
    memo = [INF] * n
    memo[start] = 0
    q = [(0, start)]

    while q:
        dist, ver = heapq.heappop(q)
        if memo[ver] < dist:
            continue
        for next_ver, next_dist in graph[ver]:
            if memo[next_ver] > dist + next_dist:
                memo[next_ver] = dist + next_dist
                heapq.heappush(q, (dist + next_dist, next_ver))

    return memo

n = int(input())
graph = [[] for i in range(n)]
for i in range(n):
    info = list(map(int, input().split()))
    for j in range(info[1]):
        graph[info[0]].append((info[j*2 + 2], info[j*2 + 3]))

memo = dijkstra(graph, 0, n)
for i, d in enumerate(memo):
    print(i, d)

Python: # -*- coding: utf-8 -*-


if __name__ == '__main__':

    n = int(input())
    M = [[float("inf") for j in range(n)] for i in range(n)]

    for i in range(n):
        l = list(map(int, input().split(" ")))
        for k in range(l[1]):
            j = l[2 + 2 * k]
            c = l[2 + 2 * k + 1]
            M[i][j] = c

    d = [float("inf")] * n

    def dijkstra(s):
        color = [0] * n
        p = [None] * n
        d[s] = 0
        p[s] = -1

        while True:
            mincost = float("inf")
            for i in range(n):
                if color[i] != 2 and d[i] < mincost:
                    mincost = d[i]
                    u = i

            if mincost == float("inf"):
                break

            color[u] = 2

            for v in range(n):
                if color[v] != 2:
                    if d[u] + M[u][v] < d[v]:
                        d[v] = d[u] + M[u][v]
                        p[v] = u
                        color[v] = 1

    dijkstra(0)
    for i in range(n):
        print(i, d[i])

Python: import heapq


def dijkstra(g, source):
    n = len(g)
    q = []
    heapq.heapify(q)
    heapq.heappush(q, (0, source))
    d = [float('inf') for _ in range(n)]
    d[source] = 0
    while len(q) > 0:
        cur = heapq.heappop(q)
        cur_pos = cur[1]
        for next in g[cur_pos]:
            next_pos = next[0]
            next_d = d[cur_pos] + next[1]
            if next_d < d[next_pos]:
                d[next_pos] = next_d
                heapq.heappush(q, (d[next_pos], next_pos))
    return d


def main():
    n = int(input())
    g = [[] for _ in range(n)]
    for _ in range(n):
        inp = list(map(int, input().split()))
        m = inp[0]
        k = inp[1]
        for i in range(k):
            g[m].append((inp[(i+1)*2], inp[(i+1)*2+1]))
    d = dijkstra(g, 0)
    for i in range(n):
        print(i, d[i])


if __name__ == '__main__':
    main()

Python: from heapq import heapify, heappush, heappop
INF = float("inf")
def MAIN():
    n = int(input())
    G = [[i, INF] for i in range(n)]
    G[0][1] = 0
    m = {}
    for _ in range(n):
        A = list(map(int, input().split()))
        m[A[0]] = {}
        for i in range(2, len(A), 2):
            m[A[0]][A[i]] = A[i + 1]
    dp = [(0, 0)]
    while dp:
        cost, u = heappop(dp)
        for v, c in m[u].items():
            if G[v][1] > G[u][1] + c:
                G[v][1] = G[u][1] + c
                heappush(dp, (G[v][1], v))
    print("\n".join(" ".join(map(str, a)) for a in G))
MAIN()

Python: INFTY = 1 << 21
WHITE = 0
GRAY = 1
BLACK = 2
 
n = int(input())
M = [list(map(int, input().split())) for i in range(n)]
 
d = [INFTY for i in range(n)]
color = [INFTY for i in range(n)]
 
for i in range(n):
    u = int(input())
    k = int(input())
    for j in range(k):
        v = int(input())
        c = int(input())
        M[u][v] = c
        
def dijkstra():
    global M, d, p, color
    d[0] = 0
    color[0] = GRAY
    while(1):
        minv = INFTY
        u = -1
        for i in range(n):
            if (minv > d[i] and color[i] != BLACK):
                u = i
                minv = d[i]
        if (u == -1):
            break
        color[u] = BLACK
        for v in range(n):
            if (color[v] != BLACK and M[u][v] != INFTY):
                if (d[v] > d[u] + M[u][v]):
                    d[v] = d[u] + M[u][v]
                    color[v] = GRAY
 
print(dijkstra())

Python: import sys
from collections import namedtuple
from heapq import heappop, heappush

Edge = namedtuple('Edage', 'to cost')
P = namedtuple('P', 'cost u')

N = int(input())

G = [[] for _ in range(N)]

for u in range(N):
  args = [int(x) for x in input().split()]
  #　不要な値を捨てる 
  args.pop(0)
  args.pop(0)

  while args:
    to = args.pop(0)
    cost = args.pop(0)
    G[u].append(Edge(to, cost))

costs = [sys.maxsize] * N
costs[0] = 0

q = [P(0, 0)]

while q:
  cost, u = heappop(q) 

  for v, c in G[u]:
    if costs[u] + c < costs[v]:
      costs[v] = costs[u] + c
      heappush(q, P(costs[v], v))

for i in range(N):
  print(i, costs[i])