Go: // Warshall–Floyd Algorithm

package main

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

var scanner = bufio.NewScanner(os.Stdin)

const INF = 2000000000

func main() {
	for scanner.Scan() {
		buf := strings.Split(scanner.Text(), " ")
		n, _ := strconv.Atoi(buf[0])
		m, _ := strconv.Atoi(buf[1])
		if n == 0 && m == 0 {
			break
		}
		c_matrix := make([][]int, m)
		for i := range c_matrix {
			c_matrix[i] = make([]int, m)
		}
		t_matrix := make([][]int, m)
		for i := range t_matrix {
			t_matrix[i] = make([]int, m)
		}
		for i := 0; i < n; i++ {
			scanner.Scan()
			buf_ := strings.Split(scanner.Text(), " ")
			a, _ := strconv.Atoi(buf_[0])
			b, _ := strconv.Atoi(buf_[1])
			c, _ := strconv.Atoi(buf_[2])
			t, _ := strconv.Atoi(buf_[3])
			c_matrix[a-1][b-1] = c
			t_matrix[a-1][b-1] = t
		}
		c_dist := make([][]int, m)
		c_prev := make([][]int, m)
		t_dist := make([][]int, m)
		t_prev := make([][]int, m)
		for i := 0; i < m; i++ {
			c_dist[i] = make([]int, m)
			c_prev[i] = make([]int, m)
			t_dist[i] = make([]int, m)
			t_prev[i] = make([]int, m)
		}
		for i := 0; i < m; i++ {
			for j := 0; j < m; j++ {
				if c_matrix[i][j] == 0 {
					c_dist[i][j] = INF
					c_prev[i][j] = -1
				} else {
					c_dist[i][j] = c_matrix[i][j]
					c_prev[i][j] = i
				}
				if t_matrix[i][j] == 0 {
					t_dist[i][j] = INF
					t_prev[i][j] = -1
				} else {
					t_dist[i][j] = t_matrix[i][j]
					t_prev[i][j] = i
				}
			}
			c_dist[i][i] = 0
			t_dist[i][i] = 0
		}
		for k := 0; k < m; k++ {
			for i := 0; i < m; i++ {
				for j := 0; j < m; j++ {
					c_newlen := c_dist[i][k] + c_dist[k][j]
					if c_newlen < c_dist[i][j] {
						c_dist[i][j] = c_newlen
						c_prev[i][j] = c_prev[k][j]
					}
				}
			}
		}
		for k := 0; k < m; k++ {
			for i := 0; i < m; i++ {
				for j := 0; j < m; j++ {
					t_newlen := t_dist[i][k] + t_dist[k][j]
					if t_newlen < t_dist[i][j] {
						t_dist[i][j] = t_newlen
						t_prev[i][j] = t_prev[k][j]
					}

				}
			}
		}
		scanner.Scan()
		k, _ := strconv.Atoi(scanner.Text())
		for i := 0; i < k; i++ {
			scanner.Scan()
			buf_ := strings.Split(scanner.Text(), " ")
			p, _ := strconv.Atoi(buf_[0])
			q, _ := strconv.Atoi(buf_[1])
			r, _ := strconv.Atoi(buf_[2])
			switch r {
			case 0:
				fmt.Println(c_dist[p-1][q-1])
			case 1:
				fmt.Println(t_dist[p-1][q-1])
			}
		}
	}
}

Python: """ Created by Jieyi on 7/28/16. """
import io
import sys
from collections import defaultdict
import heapq

if len(sys.argv) > 1:
    filename = sys.argv[1]
    inp = ''.join(open(filename, "r").readlines())
    sys.stdin = io.StringIO(inp)


def dijkstra(graph, start, total_vertices):
    h = []
    shortest_path = [0 if i == start else sys.maxsize for i in range(total_vertices + 1)]
    heapq.heappush(h, (start, 0))

    while True:
        if 0 == len(h):
            break
        vertex, value = heapq.heappop(h)

        for k, v in graph.get(vertex):
            if shortest_path[k] > value + v:
                shortest_path[k] = value + v
                heapq.heappush(h, (k, shortest_path[k]))

    return shortest_path


def algorithm():
    while True:
        n, s = map(int, input().split())
        if n == 0 and s == 0:
            break

        # Create two maps.
        g_money = defaultdict(list)
        g_time = defaultdict(list)

        # Set two maps.
        for _ in range(n):
            start, end, money, time = map(int, input().split())
            g_money[start].append((end, money))
            g_money[end].append((start, money))
            g_time[start].append((end, time))
            g_time[end].append((start, time))

        # Calculate the shortest path.
        for n in range(int(input())):
            start, end, category = list(map(int, input().split()))
            m = {0: g_money, 1: g_time}.get(category)
            ans = dijkstra(m, start, s)
            print(ans[end])


def main():
    algorithm()


if __name__ == '__main__':
    main()

Python: import copy as c
CEIL = 2000000000

def exploreMin(now, goal, mode, history, ans, lines):
    #mode=0: MinCost;mode=1: MinTime
    #print(lines)
    if now == goal:
        #print('??\????????±??????')
        return ans
    if now in history: return CEIL
    minCostOrTime = CEIL
    for destination in lines[now]:
        exploreAns = exploreMin(destination[0], goal, mode, c.deepcopy(history)+[now],
                                ans+destination[mode+1], lines)
        #print(exploreAns)
        if minCostOrTime > exploreAns: minCostOrTime = exploreAns
    return minCostOrTime
'''
def findMin(start, goal, mode):
    minAnswer=100000
    if minAnswer > xplore(start, goal, mode, []):

    return minAnswer
'''
def dprint(a):
    print('debug:', end='')
    print(a)

def main():
    input1 = input().split(' ')
    #dprint(input1)
    if input1[0] == '0': return True
    lines=[[] for i in range(int(input1[1]))]
    for lineIndex in range(int(input1[0])):
        input2 = input().split(' ')
        #print('debug:', end='')
        #print(input2)
        lines[int(input2[0])-1].append([int(input2[1])-1, int(input2[2]), int(input2[3])])
        lines[int(input2[1])-1].append([int(input2[0])-1, int(input2[2]), int(input2[3])])
    #print(lines[0][0][1])
    setnum = int(input())
    #a = '\n'
    for out in range(setnum):
        #if out==setnum-1: a=''
        input3 = input().split(' ')
        #print([].append(1))
        print(exploreMin(int(input3[0])-1, int(input3[1])-1, int(input3[2]), [], 0, lines))

if __name__ == '__main__':
    while True:
        if main(): break

Python: def warshall_floyd(v_count: int, matrix: list) -> list:
    """ ワーシャルフロイド
    :param v_count: 頂点数
    :param matrix: 隣接行列(到達不能はfloat("inf"))
    """
    # 到達不能をfloat("inf")にしておけば余計なチェックを入れなくても
    # inf > inf+(-1) のような到達不能＋負辺が繋がってしまうことはない
    for i in range(v_count):
        for j, c2 in enumerate(row[i] for row in matrix):
            for k, (c1, c3) in enumerate(zip(matrix[j], matrix[i])):
                if c1 > c2+c3:
                    matrix[j][k] = c2+c3
    return matrix

while True:
    e_count, v_count = map(int, input().split())
    if not e_count:
        break
    inf = float("inf")
    edges_cost, edges_time = [[inf]*v_count for _ in [0]*v_count], [[inf]*v_count for _ in [0]*v_count]
    for _ in [0]*e_count:
        a, b, cost, time = map(int, input().split())
        a, b = a-1, b-1
        edges_cost[a][b] = cost
        edges_cost[b][a] = cost
        edges_time[a][b] = time
        edges_time[b][a] = time

    warshall_floyd(v_count, edges_cost)
    warshall_floyd(v_count, edges_time)

    for _ in [0]*int(input()):
        p, q, r = map(int, input().split())
        print((edges_time if r else edges_cost)[p-1][q-1])