Go: package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
	"strconv"
)

const NIL = -1

type Node struct {
	id     int
	weight int
}

func init() {
	sc.Split(bufio.ScanWords)
}

type NodeHeap []Node

func (h NodeHeap) Len() int           { return len(h) }
func (h NodeHeap) Less(i, j int) bool { return h[i].weight < h[j].weight }
func (h NodeHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *NodeHeap) Push(x interface{}) {
	*h = append(*h, x.(Node))
}

func (h *NodeHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	num, _ := strconv.Atoi(scanString())
	return num
}

func scanString() string {
	sc.Scan()
	return sc.Text()
}

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	n := scanInt()

	list := make([][]int, n)
	weight := make([]int, n)
	for i := range list {
		list[i] = make([]int, n)
		weight[i] = NIL
		for j := range list[i] {
			list[i][j] = NIL
		}
	}

	for i := 0; i < n; i++ {
		u := scanInt()
		k := scanInt()
		for j := 0; j < k; j++ {
			v := scanInt()
			w := scanInt()
			list[u][v] = w
		}
	}

	start := Node{id: 0, weight: 0}
	h := &NodeHeap{start}
	heap.Init(h)

	for h.Len() > 0 {
		node := heap.Pop(h).(Node)
		if weight[node.id] != NIL {
			continue
		}
		weight[node.id] = node.weight

		for i, w := range list[node.id] {
			if w == NIL {
				continue
			}
			heap.Push(h, Node{id: i, weight: w + node.weight})
		}
	}

	w := bufio.NewWriter(os.Stdout)
	for i := 0; i < n; i++ {
		fmt.Fprint(w, i)
		fmt.Fprint(w, " ")
		fmt.Fprint(w, weight[i])
		fmt.Fprintln(w)
	}
	w.Flush()
}

Python: import sys
from operator import add

n = int(sys.stdin.readline().strip())
A = [ [0] for i in range(n)]
for i in range(n):
	temp = map(int ,sys.stdin.readline().strip().split(" "))
	A[i] = temp


weight = [None for i in range(n)]
mitayatu=[False for i in range(n)]

def min(array):
	temp = 100000
	index= 0
	for i in range(n):
		if array[i] is not None and mitayatu[i]==False:
			if temp>=array[i]:
				temp = array[i]
				index = i
	return index

def owari():
	for i in mitayatu:
		if i is False:
			return False
	return True
# zero origin
def prim(nodeid):
	#print(nodeid)
	if owari() == True:
		return
	if mitayatu[nodeid]==True:
		return
	mitayatu[nodeid]=True
	for i in range(n):
		if A[nodeid][i]!=-1:
			if weight[i] is None:
				weight[i]=A[nodeid][i]
			elif weight[i]>A[nodeid][i] and mitayatu[i]==False:
				weight[i]=A[nodeid][i]+weight[nodeid]
	prim(min(weight))

weight[0]=0
prim(0)

#print(weight)
print(reduce(add, weight))

Python: from sys import maxsize

WHITE = 0
GRAY = 1
BLACK = 2


def read_adj():
    n = int(input())
    adj_list = [[] for _ in range(n)]
    for i in range(n):
        u, _, *rest = [int(x) for x in input().split()]
        for i in range(0, len(rest) - 1, 2):
            adj_list[u].append((rest[i], rest[i + 1]))

    return n, adj_list


def shortest_path(n, adj_list):
    color = [WHITE] * n
    dist = [maxsize] * n

    dist[0] = 0
    color[0] = GRAY

    while True:
        minv = maxsize
        u = -1
        for i in range(n):
            if minv > dist[i] and color[i] != BLACK:
                u = i
                minv = dist[i]

        if u == -1:
            break
        color[u] = BLACK

        for v, c in adj_list[u]:
            if dist[u] + c < dist[v]:
                dist[v] = dist[u] + c
                color[v] = GRAY
                
    return dist


def print_dist(dist):
    for u, d in enumerate(dist):
        print(u, d)


def main():
    n, adj_list = read_adj()
    dist = shortest_path(n, adj_list)
    print_dist(dist)


if __name__ == '__main__':
    main()

Python: # input
n = int(input())
A = [[-1] * n for i in range(n)]
for _ in range(n):
    line = list(map(int, input().split()))
    u = line.pop(0)
    k = line.pop(0)
    for i in range(k):
        v = line.pop(0)
        c = line.pop(0)
        A[u][v] = c
    
# 変数定義
inf = 100 * 100000 + 1
M = A.copy()
M = [[a if a > -1 else inf for a in line] for line in M]
d = [inf] * n
V = set([i for i in range(n)]) #nodeの一覧
T = set() #探索済みnodeの一覧

# 探索
start = 0
target = start
d[target] = 0
T.add(target)
while V != T:
    for i in (V - T):
        if d[target] + M[target][i] < d[i]:
            d[i] = d[target] + M[target][i]

    min_wheght = min([d[i] for i in (V - T)])
    min_path = [i for i in (V - T) if d[i] == min_wheght][0]
    target = min_path
    T.add(target)

# 出力
for i in range(n):
    print(f"{i} {d[i]}")

Python: n=int(input())
M=[[-1]*n for _ in[0]*n]
for _ in[0]*n:
 e=list(map(int,input().split()))
 for i in range(e[1]):k=2*-~i;M[e[0]][e[k]]=e[k+1]
d=[0]+[1e6]*~-n
c=[1]*n
while 1:
 m,u=1e6,-1
 for i in range(n):
  if m>d[i]and c[i]:m,u=d[i],i
 if u<0:break
 c[u]=0
 for v in range(n):
  if c[v]and 1+M[u][v]and d[v]>d[u]+M[u][v]:
   d[v]=d[u]+M[u][v]
for i in range(i):print(i,d[i])

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

import heapq
q = [] # プライオリティキュー


n = int(input())
V = dict()
d = dict()

for i in range(n):
    data = list(map(int, input().split()))
    V[data[0]] = data[2:]
    d[data[0]] = float('inf')

d[0] = 0
heapq.heappush(q, (0, 0)) #(d[id], id)
S = set()

while len(S) != len(V):
    dist, node_id = heapq.heappop(q)
    S.add(node_id)
    for u, c in zip(V[node_id][0::2], V[node_id][1::2]): #隣接ノード
        if c + d[node_id] < d[u]:
            d[u] = c + d[node_id]
            heapq.heappush(q, (d[u], u))
            #print("Update:", u, d[u])
for i in range(n):
    print(i, d[i])

Python: import heapq


class ShortestPath:
    """Dijkstra's algorithm : find the shortest path from a vertex
       Complexity: O(E + log(V))
       used in GRL1A(AOJ)
    """

    def __init__(self, V, E, start, INF=10**9):
        """ V: the number of vertexes
            E: adjacency list (all edge in E must be 0 or positive)
            start: start vertex
            INF: Infinity distance
        """
        self.V = V
        self.E = E
        self.dijkstra(start, INF)

    def dijkstra(self, start, INF):
        que = list()
        self.distance = [INF] * self.V  # distance from start
        self.prev = [-1] * self.V  # prev vertex of shortest path
        self.distance[start] = 0
        heapq.heappush(que, (0, start))

        while len(que) > 0:
            dist, fr = heapq.heappop(que)
            if self.distance[fr] < dist:
                continue
            for to, cost in self.E[fr]:
                if self.distance[fr] + cost < self.distance[to]:
                    self.distance[to] = self.distance[fr] + cost
                    heapq.heappush(que, (self.distance[to], to))
                    self.prev[to] = fr

    def getPath(self, end):
        path = [end]
        while self.prev[end] != -1:
            end = self.prev[end]
        return path[::-1]
V = int(input())
edge = [[] for _ in range(V)]
for _ in range(V):
    u, _, *e = map(int, input().split())
    for t, d in zip(e[::2], e[1::2]):
        edge[u].append((t, d))

sp = ShortestPath(V, edge, 0)
for i, d in enumerate(sp.distance):
    print(i, d)

Python: from heapq import heappush, heappop, heappushpop, heapreplace, heapify

#隣接リスト作成
v = int(input())
edge_list = [[] for _ in range(v)]
for i in range(v):
    l = list(map(int, input().split()))
    for j in range(1,l[1]+1):
        edge_list[l[0]].append([l[2*j+1],l[2*j]])

def dijkstra(v, edges, start):
    d = [float("inf")] * v
    visited = [False] * v
    d[start] = 0
    visited[start] = 0
    hq = []
    for i in edges[start]:
        d[i[1]] = i[0]
        heappush(hq, i)

    while hq:
        x, y = heappop(hq)
        #もし更新する必要がないならこれ以降の処理を行わない
        if d[y] < x:
            continue
        d[y] = x
        visited[y] = True
        for n in edges[y]:
            if not visited[n[1]]:
                hq.append([x + n[0], n[1]])
        heapify(hq)
    return d

for index, d in enumerate(dijkstra(v, edge_list,0)):
    print(index,d)