Problem:
 Score : 400 points    Problem Statement There are N towns in the State of Atcoder, connected by M bidirectional roads.  The i -th road connects Town A_i and B_i and has a length of C_i .  Joisino is visiting R towns in the state, r_1,r_2,..,r_R (not necessarily in this order).  She will fly to the first town she visits, and fly back from the last town she visits, but for the rest of the trip she will have to travel by road.  If she visits the towns in the order that minimizes the distance traveled by road, what will that distance be?      Constraints  2≤N≤200  1≤M≤N×(N-1)/2  2≤R≤min(8,N) ( min(8,N) is the smaller of 8 and N .)  r_i≠r_j (i≠j)  1≤A_i,B_i≤N, A_i≠B_i  (A_i,B_i)≠(A_j,B_j),(A_i,B_i)≠(B_j,A_j) (i≠j)  1≤C_i≤100000  Every town can be reached from every town by road.  All input values are integers.         Input Input is given from Standard Input in the following format:  N  M  R  r_1  ...  r_R  A_1  B_1  C_1  :  A_M  B_M  C_M       Output Print the distance traveled by road if Joisino visits the towns in the order that minimizes it.        Sample Input 1 3 3 3
1 2 3
1 2 1
2 3 1
3 1 4      Sample Output 1 2  For example, if she visits the towns in the order of 1 , 2 , 3 , the distance traveled will be 2 , which is the minimum possible.       Sample Input 2 3 3 2
1 3
2 3 2
1 3 6
1 2 2      Sample Output 2 4  The shortest distance between Towns 1 and 3 is 4 . Thus, whether she visits Town 1 or 3 first, the distance traveled will be 4 .       Sample Input 3 4 6 3
2 3 4
1 2 4
2 3 3
4 3 1
1 4 1
4 2 2
3 1 6      Sample Output 3 3

Solution (Python):
class WarshallFloyd():
    def __init__(self, N):
        self.N = N
        self.d = [[float("inf") for i in range(N)]
                  for i in range(N)]  

    def add(self, u, v, c, directed=False):
        """
        0-indexedであるに注意
        u = from, v = to, c = cost
        directed = Trueなら、有向グラフである
        """
        if directed is False:
            self.d[u][v] = c
            self.d[v][u] = c
        else:
            self.d[u][v] = c

    def WarshallFloyd_search(self):
        
        
        for k in range(self.N):
            for i in range(self.N):
                for j in range(self.N):
                    self.d[i][j] = min(
                        self.d[i][j], self.d[i][k] + self.d[k][j])
        for i in range(self.N):
            self.d[i][i] = 0
        return self.d


import itertools

N, M, R = map(int, input().split())
r = list(map(int, input().split()))
graph = WarshallFloyd(N)
for i in range(M):
    a, b, c = map(int, input().split())
    graph.add(a-1, b-1, c)

d = graph.WarshallFloyd_search()
ans = float('inf')
for each in itertools.permutations(r):
    cur = 0
    for i in range(R - 1):
        cur += d[each[i] - 1][each[i + 1] - 1]
    ans = min(ans, cur)

print(ans)

Solution (Python):
from itertools import permutations

N, M, R = map(int,input().split())
r = list(map(int,input().split()))

possible = permutations(r,R)
dist = [[float("inf") for k in range(N)]for i in range(N)]

for i in range(N):
    dist[i][i] = 0

for i in range(M):
    a,b,c = map(int,input().split())
    a -= 1
    b -= 1
    dist[a][b] = c
    dist[b][a] = c

for i in range(N):
    for j in range(N):
        for k in range(N):
            dist[j][k] = min(dist[j][k],dist[j][i]+dist[i][k])

Ans = float("inf")
for pos in possible:
    ans = 0
    for i in range(R-1):
        ans += dist[pos[i]-1][pos[i+1]-1]

    Ans = min(Ans,ans)

print(Ans)

Solution (Python):
from functools import reduce
import math
import itertools

def main():
    
    
    
    

    
    
    
    
    
    

    
    

    
    
    
    
    
    
    
    
    
    INF = float("inf")

    
    MOD = 10**9+7
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    
    
    
    
    N,M,R = (int(_) for _ in input().split())
    r = list(int(_)-1 for _ in input().split())
    a = []
    b = []
    c = []
    for i in range(M):
        s1,s2,s3 = (int(_) for _ in input().split())
        a.append(s1-1)
        b.append(s2-1)
        c.append(s3)
    d = []
    for i in range(N):
        d.append(list(INF for _ in range(N)))
        
    for i in range(N):
        for j in range(N):
            if i == j:
                d[i][j] = 0
    for i in range(M):
        if d[a[i]][b[i]] > c[i]:
            d[a[i]][b[i]] = c[i]
            d[b[i]][a[i]] = c[i]
    for k in range(N):
        for i in range(N):
            for j in range(N):
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]
    ans = INF
    for nodes in list(itertools.permutations(r)):
        cost = 0
        for i in range(len(nodes)-1):
            cost += d[nodes[i]][nodes[i+1]]
        ans = min(ans,cost)
    print(ans)
if __name__ == '__main__':
    main()

Solution (Python):

import sys
import heapq
import copy
import itertools

inf = float('inf')

def path(u, v):
    return frozenset((u, v))


class Graph_dijkstra(object):
    def __init__(self, V: "List[int]", E: "Set[FrozenSet[int, int]]", L: "Dict[FrozenSet[int, int], int]"):
        self.V = V
        self.E = E
        self.L = L
        self.adjacent = self.init_adjacent() 
        self.shortest_path = self.init_shortest_path() 
    
    def init_adjacent(self):
        ret = {v: [] for v in self.V}
        for e in self.E:
            el = list(e)
            ret[el[0]].append(el[1])
            ret[el[1]].append(el[0])
        return ret
    
    def init_shortest_path(self):
        ret = {path(s, g): inf for s, g in itertools.permutations(self.V, 2)}
        for v in self.V:
            ret[path(v, v)] = 0
        return ret
    
    def dijkstra(self, s: int):
        D = {v: inf for v in self.V}
        D[s] = 0
        prev = {v: None for v in self.V}
        Q = [(0, s)]

        while len(Q) > 0:
            du, u = heapq.heappop(Q)
            for v in self.adjacent[u]:
                e = path(u, v)
                alt = du + self.L[e]
                if alt < D[v]:
                    D[v] = alt
                    prev[v] = u
                    heapq.heappush(Q, (D[v], v))

        for v in self.V:
            self.shortest_path[path(s, v)] = D[v]

    def find_shortest_path(self, pair: "FrozenSet[int, int]"):
        d = self.shortest_path[pair]
        if d < inf:
            return d
        s = list(pair)[0]
        self.dijkstra(s)
        return self.shortest_path[pair]

def solve(N: int, M: int, R: int, r: "List[int]", A: "List[int]", B: "List[int]", C: "List[int]"):
    V = list(range(N))
    E = set()
    L = dict()
    
    for i in range(M):
        e = path(A[i], B[i])
        E.add(e)
        L[e] = C[i]

    G = Graph_dijkstra(V, E, L)
    for ri in r:
        G.dijkstra(ri)
    shortest = inf
    for p in itertools.permutations(r):
        path_len = 0
        for i in range(len(p)-1):
            path_len += G.find_shortest_path(path(p[i], p[i+1]))
        if path_len < shortest:
            shortest = path_len
    
    print(shortest)
    return



def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  
    M = int(next(tokens))  
    R = int(next(tokens))  
    r = [ int(next(tokens))-1 for _ in range(R) ]  
    A = [int()] * (M)  
    B = [int()] * (M)  
    C = [int()] * (M)  
    for i in range(M):
        A[i] = int(next(tokens))-1
        B[i] = int(next(tokens))-1
        C[i] = int(next(tokens))
    solve(N, M, R, r, A, B, C)

if __name__ == '__main__':
    main()

Solution (Python):
import itertools
N,M,R=map(int,input().split())
r=list(map(int,input().split()))

L=[[10**15 for i in range(N)]for j in range(N)]
for i in range(N):
    L[i][i]=0
for a in range(M):
    A,B,C=map(int,input().split())
    L[A-1][B-1]=C
    L[B-1][A-1]=C



for c in range(N):
    for a in range(N):
        for b in range(N):
            L[a][b]=min(L[a][b],L[a][c]+L[c][b])

LIS=list(itertools.permutations(r))

ans=10**15

for i in range(len(LIS)):
    cnt=0
    for x in range(1,len(r)):
        
        cnt+=L[LIS[i][x-1]-1][LIS[i][x]-1]
    if cnt<ans:
        ans=cnt
print(ans)

Solution (Python):



def warshall_floyd(dist):
    
    for k in range(N):
        for i in range(N):
            for j in range(N):
                dist[i][j] = min(dist[i][j],dist[i][k] + dist[k][j])
    return dist

N,M,R=map(int,input().split())
r=list(map(int,input().split()))

dist = [[float("inf") for i in range(N)] for i in range(N)] 

for i in range(M):
    a,b,c = map(int,input().split())
    dist[a-1][b-1] = c
    dist[b-1][a-1] = c
for i in range(N):
    dist[i][i] = 0 
dist=warshall_floyd(dist)

ever=[]
MIN=100000000
def ans_func(ever):
    global R
    global r
    global dist
    global MIN
    
    if len(ever) == R:
        if R == 2:
            kari=dist[ever[0]][ever[1]]
            MIN=min(MIN,kari)
        else:
            kari=0
            for i in range(R-1):
                kari+=dist[ever[i]][ever[i+1]]
            MIN=min(MIN,kari)
    else:
        i=0
        for i in range(R):
            if r[i]-1 in ever:
                pass
            else:
                ever.append(r[i]-1)
                ans_func(ever)
                ever.remove(r[i]-1)
    return
ans_func(ever)
print(MIN)

Solution (Python):
n, m, r = map(int,input().split())
r_list = list(map(lambda x:int(x)-1,input().split()))
INF = float('inf')
edge = []
for _ in range(m):
    a,b,c = map(int,input().split())
    edge.append([a-1,b-1,c])
def warshall_floyd(n,edge):
    graph = [[INF]*n for _ in range(n)]
    for i in range(n):
        graph[i][i] = 0
    for a, b, c in edge:
        graph[a][b] = c
        graph[b][a] = c
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if graph[i][k] + graph[k][j] < graph[i][j] :
                    graph[i][j] = graph[i][k] + graph[k][j]
    return graph
g = warshall_floyd(n,edge)
from itertools import permutations
ans = INF
for arr in permutations(range(r)):
    tmp = 0
    for a,b in zip(arr,arr[1:]):
        t1,t2 = r_list[a],r_list[b]
        tmp += g[t1][t2]
    ans = min(ans,tmp)
print(ans)

Solution (Python):
import itertools
inf = float('inf')



def warshall_floyd(dist,n):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if i == j:
                    dist[i][j] = 0
                elif dist[i][j] > dist[i][k] + dist[k][j]:
                    dist[i][j] = dist[i][k] + dist[k][j]

N,M,R = map(int,input().split())
r = [int(e)-1 for e in input().split()]

dist = [[inf]*N for _ in range(N)]

for _ in range(M):
    A,B,C = map(int,input().split())
    A -= 1; B -= 1
    dist[A][B] = C
    dist[B][A] = C

warshall_floyd(dist,N)

ans = inf

for order in itertools.permutations(r):
    res = 0
    for i in range(R-1):
        res += dist[order[i]][order[i+1]]
    if res < ans:
        ans = res

print(ans)

Solution (Python):
from itertools import permutations
N, M, R = map(int, input().split())
r = list(map(lambda x: int(x) - 1, input().split()))
G = [[float('inf')] * N for i in range(N)]
for i in range(M):
    a, b, c = map(int, input().split())
    a, b = a - 1, b - 1
    G[a][b] = c
    G[b][a] = c


for k in range(N):
    G[k][k] = 0
    for i in range(N):
        for j in range(N):
            G[i][j] = min(G[i][j], G[i][k] + G[k][j])


ans = float('inf')
for perm in permutations(r):
    tmp = 0
    for i in range(R - 1):
        tmp += G[perm[i]][perm[i + 1]]
    ans = min(ans, tmp)

print(ans)

Solution (Python):
import heapq
from itertools import permutations
n, m, r = [int(item) for item in input().split()]
rs = [int(item) for item in input().split()]
abc = [[int(item) for item in input().split()] for _ in range(m)]
INF = 10**9

class Dijkstra:
    def __init__(self, adj):
        self.adj = adj
        self.num = len(adj)
        self.dist = [INF] * self.num
        self.prev = [INF] * self.num
        self.q = []

    def reset(self):
        self.dist = [INF] * self.num
        self.prev = [INF] * self.num
        self.q = []

    def calc(self, start, goal=None):
        self.dist[start] = 0
        heapq.heappush(self.q, (0, start))
        while len(self.q) != 0:
            prov_cost, src = heapq.heappop(self.q)
            if self.dist[src] < prov_cost:
                continue
            for dest in range(self.num):
                cost = self.adj[src][dest]
                if cost != INF and self.dist[dest] > self.dist[src] + cost:
                    self.dist[dest] = self.dist[src] + cost
                    heapq.heappush(self.q, (self.dist[dest], dest))
                    self.prev[dest] = src
        if goal is not None:
            return self.get_path(goal)
        else:
            return self.dist

    def get_path(self, goal):
        path = [goal]
        dest = goal

        while self.prev[dest] != INF:
            path.append(self.prev[dest])
            dest = self.prev[dest]
        return list(reversed(path))

path = [[INF] * n for _ in range(n)]
short_path = [[INF] * n for _ in range(n)]
for i in range(n):
    path[i][i] = 0
for a, b, c in abc:
    path[a-1][b-1] = path[b-1][a-1] = c

dij = Dijkstra(path)
for item in rs:
    for i in range(n):
        short_path[item-1][i] = dij.calc(item-1)[i]
    dij.reset()

ans = INF
for pattern in permutations(rs):
    distance = 0
    for i in range(1,r):
        distance += short_path[pattern[i-1]-1][pattern[i]-1]
    ans = min(ans, distance)
print(ans)

Solution (Python):
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


from functools import reduce
from itertools import permutations

from heapq import heappush, heappop

def dijkstra(graph:list, node:int, start:int) -> list:
    
    INF = float("inf")
    dist = [INF]*node
    
    
    dist[start] = 0
    heap = [(0,start)]
    
    
    while heap:
        cost, cur_node = heappop(heap)
        
        for nex_cost, nex_node in graph[cur_node]:
            dist_cand = dist[cur_node] + nex_cost
            if dist_cand < dist[nex_node]:
                dist[nex_node] = dist_cand
                heappush(heap, (dist[nex_node], nex_node))
    
    return dist

def find_dist(fr: int, to: int):
    return graph[fr][to]

n,m,rn = li()
r = list(li_())
adj_list = [[] for _ in range(n)]
for _ in range(m):
    a,b,c = li()
    a -= 1
    b -= 1
    adj_list[a].append((c, b))
    adj_list[b].append((c, a))
    
graph = [[0]*rn for _ in range(rn)]
for i, ri in enumerate(r):
    dist = dijkstra(adj_list, n, ri)
    for j, rj in enumerate(r):
        graph[i][j] = dist[rj]

ans = float('inf')
for route in permutations(range(len(r)), len(r)):
    cand = 0
    for i,j in zip(route[:-1], route[1:]):
        cand += graph[i][j]
    
    ans = min(ans, cand)

print(ans)

Solution (Python):
import itertools

N, M, R = map(int, input().split())
r = [int(s) - 1 for s in input().split()]
a, b, c = [0] * M, [0] * M, [0] * M
for i in range(M):
    a[i], b[i], c[i] = map(int, input().split())
    a[i] -= 1
    b[i] -= 1

wf = [[float('inf')] * N for _ in range(N)]
for i in range(M):
    wf[a[i]][b[i]] = c[i]
    wf[b[i]][a[i]] = c[i]

for k, i, j in itertools.product(range(N), repeat=3):
    wf[i][j] = min(wf[i][j], wf[i][k] + wf[k][j])

x = float('inf')
for route in itertools.permutations(r):
    y = sum(wf[route[i]][route[i + 1]] for i in range(R - 1))
    x = min(x, y)

print(x)

Solution (Python):
from itertools import permutations 
inf=10**9
n, m, r1 = map(int, input().split())
r=list(map(int, input().split()))
abc=[list(map(int, input().split())) for _ in range(m)]
d=[[inf]*n for i in range(n)]
for ai, bi, ci in abc:
    d[ai-1][bi-1]=ci
    d[bi-1][ai-1]=ci
for k in range(n):
    for i in range(n-1):
        for j in range(i, n):
            dk=d[i][k]+d[k][j]
            if d[i][j]>dk:
                d[j][i]=dk
                d[i][j]=dk
permutations(r)
ans=inf
p=list(permutations(r))
for pi in p:
    res=0
    for i in range(r1-1):
        res+=d[pi[i]-1][pi[i+1]-1]
    if ans>res:
        ans=res
print(ans)

Solution (Python):
from itertools import permutations 
inf=10**9
n, m, r1 = map(int, input().split())
r=list(map(int, input().split()))
abc=[list(map(int, input().split())) for _ in range(m)]
d=[[inf]*n for i in range(n)]
for ai, bi, ci in abc:
    d[ai-1][bi-1]=ci
    d[bi-1][ai-1]=ci
for k in range(n):
    for i in range(n-1):
        for j in range(i, n):
            dk=d[i][k]+d[k][j]
            if d[i][j]>dk:
                d[j][i]=dk
                d[i][j]=dk
permutations(r)
ans=inf
for pi in permutations(r):
    res=0
    for i in range(r1-1):
        res+=d[pi[i]-1][pi[i+1]-1]
    if ans>res:
        ans=res
print(ans)

Solution (Python):
from itertools import permutations
N, M, R = map(int, input().split())
r = list(map(int, input().split()))
E = [list(map(int, input().split())) for _ in range(M)]
INF = 10 ** 9
d = [[INF for j in range(N)] for i in range(N)]
for i, j, c in E:
    d[i - 1][j - 1] = c
    d[j - 1][i - 1] = c
for k in range(N):
    for i in range(N - 1):
        for j in range(i, N):
            dk = d[i][k] + d[k][j]
            if d[i][j] > dk:
                d[i][j] = dk
                d[j][i] = dk
ans = 10 ** 9
for ri in permutations(r):
    x = 0
    for i in range(R - 1):
        x += d[ri[i] - 1][ri[i + 1] - 1]
    if ans > x:
        ans = x
print(ans)

Solution (Python):
def getN():
    return int(input())

def getlist():
    return list(map(int, input().split()))

import heapq
inf = 1000000000
ans = inf

def dijkstra(n, graph, start):
    
    h = []
    routes = [[inf, i] for i in range(n)]
    routes[start][0] = 0
    heapq.heappush(h, routes[start][1])
    while(h):
        cur = heapq.heappop(h)
        for edge in graph[cur]:
            target, cost = edge
            if routes[target][0] > routes[cur][0] + cost:
                routes[target][0] = routes[cur][0] + cost
                heapq.heappush(h, routes[target][1])

    return [route[0] for route in routes]


def dfs(depth, rlist, tmpcost, tmppos, dist):
    if depth == r-1:
        
        return tmpcost
    else:
        ans = 100000000
        for rnum in rlist:
            if flag[rnum] == 0:
                flag[rnum] = 1
                
                returncost = dfs(depth+1, rlist, tmpcost+dist[rnum-1][tmppos-1], rnum, dist)
                flag[rnum] = 0
                if ans > returncost:
                    ans = returncost
        return ans

def floyd_nanotka(n):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if(dist[i][k] + dist[k][j] <  dist[i][j]):
                    dist[i][j] = dist[i][k] + dist[k][j]


n, m, r = getlist()
graph = [[] for i in range(n)]
rlist = getlist()
dist = [[inf for i in range(n)] for j in range(n)]
for i in range(n):
    dist[i][i] = 0

for i in range(m):
    v1, v2, cost = getlist()
    dist[v1-1][v2-1] = cost
    dist[v2-1][v1-1] = cost



floyd_nanotka(n)

flag = [0 for i in range(n+1)]
ans_candidate = []
for i in rlist:
    flag[i] = 1
    ans_candidate.append(dfs(0, rlist, 0, i, dist))
    flag[i] = 0

print(min(ans_candidate))

Solution (Python):
from itertools import permutations as pe
from scipy.sparse.csgraph import floyd_warshall as wf
n,m,r=map(int,input().split())
s=[[(0 if i==j else float("inf"))for j in range(n+1)]for i in range(n+1)]
g=list(pe(list(map(int,input().split()))))
for i in range(m):
    a,b,c=map(int,input().split())
    s[a][b]=c
    s[b][a]=c
s=wf(s,directed=False)
k=float("inf")
for i in range(len(g)):
    d=g[i]
    c=0
    for j in range(1,len(d)):
        c+=s[d[j-1]][d[j]]
        if c>=k:
            break
    else:
        k=min(c,k)
print(int(k))

Solution (Python):
from scipy.sparse.csgraph import floyd_warshall as wf
import itertools

N, M, R = map(int, input().split())
r = [int(i) for i in input().split()]

G = [[float('inf')] * N for _ in range(N)]
for i in range(N):
    G[i][i] = 0
for _ in range(M):
    i, j, k = map(int, input().split())
    G[i - 1][j - 1] = k
    G[j - 1][i - 1] = k
    
wf = wf(G)

ans = float('inf')
for perm in itertools.permutations(r):
    tmp = 0
    for i in range(len(perm) - 1):
        tmp += wf[perm[i] - 1][perm[i + 1] - 1]
    ans = min(ans, tmp)
    
print(int(ans))

Solution (Python):
from itertools import permutations

def warshall_floyd(V, E):
    INF = 10 ** 9
    d = [[INF for j in range(V)] for i in range(V)]
    for i, j, c in E:
        d[i - 1][j - 1] = c
        d[j - 1][i - 1] = c
    for k in range(V):
        for i in range(V - 1):
            for j in range(i, V):
                dk = d[i][k] + d[k][j]
                if d[i][j] > dk:
                    d[i][j] = dk
                    d[j][i] = dk
    return d

N, M, R = map(int, input().split())
r = list(map(int, input().split()))
E = [list(map(int, input().split())) for _ in range(M)]
d = warshall_floyd(N, E)

ans = 10 ** 9
for ri in permutations(r):
    x = 0
    for i in range(R - 1):
        x += d[ri[i] - 1][ri[i + 1] - 1]
    if ans > x:
        ans = x
print(ans)

Solution (Python):
import sys
import numpy as np
from scipy.sparse.csgraph import floyd_warshall
from itertools import permutations

def main():
    input = sys.stdin.readline
    N, M, R = map(int, input().split())
    r = list(map(int, input().split()))

    INF = float('inf')
    A = [[INF for _ in range(N)] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        A[a-1][b-1] = c
        A[b-1][a-1] = c

    G = floyd_warshall(np.array(A))

    ans = INF
    for root in permutations(r):
        cur = 0
        for i in range(R-1):
            s, g = root[i] -1, root[i+1] - 1
            cur += G[s][g]

        ans = min(ans, cur)

    return int(ans)


if __name__ == '__main__':
    print(main())

Solution (Python):
import sys
import numpy as np
from scipy.sparse.csgraph import floyd_warshall
from itertools import permutations


def main():
    input = sys.stdin.readline
    N, M, R = map(int, input().split())
    r = list(map(int, input().split()))

    INF = 10**9
    A = [[INF for _ in range(N)] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        A[a-1][b-1] = c
        A[b-1][a-1] = c

    D = np.array(A, dtype=int)
    G = floyd_warshall(D)

    """
    ans = INF
    for start in r[:2]:
        passed = [start]
        temp_ans = 0
        while len(passed) < len(r):
            cur = INF
            next_start = -1
            for dest in r:
                if dest in passed:
                    continue

                if A[start-1][dest-1] < cur:
                    next_start = dest
                    cur = A[start-1][dest-1]

            passed.append(next_start)
            start = next_start
            temp_ans += cur

        ans = min(ans, temp_ans)
    """

    ans = INF
    for root in permutations(r):
        cur = 0
        for i in range(R-1):
            s, g = root[i] -1, root[i+1] - 1
            cur += G[s][g]

        ans = min(ans, cur)

    return int(ans)


if __name__ == '__main__':
    print(main())

Solution (Python):
N,M,R=map(int,input().split())
X=list(map(int,input().split()))
from collections import defaultdict
from collections import deque
branch=defaultdict(set)
for m in range(M):
    a,b,c=map(int,input().split())
    branch[a]|={(b,c)}
    branch[b]|={(a,c)}
def makedist(x):
    dist=[float('inf')]*(N+1)
    dist[x]=0
    check={x,}
    while len(check)>0:
        now=check.pop()
        for b in branch[now]:
            if dist[now]+b[1]<dist[b[0]]:
                dist[b[0]]=dist[now]+b[1]
                check|={b[0],}
    return dist
data=dict()
for x in X:
    data[x]=makedist(x)
def roop(now,D,notvisit,ans):
    if len(notvisit)==0:
        return min(D,ans)
    for nex in notvisit:
        ans=roop(nex,D+data[now][nex],notvisit-{nex,},ans)
    return ans
ans=float('inf')
for x in X:
    ans=min(ans,roop(x,0,set(X),float('inf')))
print(ans)

Solution (Python):
import itertools
import math
from collections import deque
from collections import defaultdict
from itertools import permutations
import heapq
INF = float("inf")

N,M,R = map(int,input().split())
r = list(map(int,input().split()))
adj_cost = defaultdict(set)

for i in range(M):
    a, b, c = map(int, input().split())
    adj_cost[a-1].add((b-1, c))
    adj_cost[b-1].add((a-1, c))

def dijkstra(v):
    d = [INF] * N
    d[v] = 0
    hq =[(0,v)]

    while hq:
        u = heapq.heappop(hq)[1]
        for (v,c) in adj_cost[u]:
            if d[v] > d[u] + c:
                d[v] = d[u] +c
                heapq.heappush(hq,(d[u]+c,v))
    return d

ans = INF
table = {}
for i in r:
    table[i-1] = dijkstra(i-1)

for each in permutations(r):
    dis = 0
    for i in range(R-1):
        dis += table[each[i]-1][each[i+1]-1]

    ans = min(ans,dis)
print(ans)

Solution (Python):
import heapq


def construct_graph(A, B, C):
    M = len(A)
    graph = {}
    for i in range(M):
        a = A[i]
        b = B[i]
        c = C[i]
        if a not in graph:
            graph[a] = {}
        if b not in graph:
            graph[b] = {}
        graph[a][b] = c
        graph[b][a] = c
    return graph


def dijkstra(graph, s, t):
    q = [(0, s)]
    fix = set()
    d = {}
    d[s] = 0
    while len(q) > 0:
        cur_d, n = heapq.heappop(q)
        if n in fix:
            continue
        fix.add(n)
        if n == t:
            break
        for v in graph[n]:
            if v in fix:
                continue
            c = graph[n][v]
            if v not in d or d[v] > d[n] + c:
                d[v] = d[n] + c
            heapq.heappush(q, (d[v], v))
    return d[t]


def dijkstra_all(graph, nodes):
    d = {}
    for n in nodes:
        d[n] = {}
        for n2 in nodes:
            if n == n2: 
                continue
            if n2 not in d:
                d[n2] = {}
            d[n][n2] = dijkstra(graph, n, n2)
            d[n2][n] = d[n][n2]
    return d


def tsp_dist(graph):
    graph[-1] = {}
    for n in graph:
        if n == -1: continue
        graph[-1][n] = 0
    return tsp(graph, set(), -1)


def tsp(graph, visited, s):
    if len(visited) + 1 == len(graph):
        return 0
    min_d = None
    for n in graph[s]:
        if n in visited: continue
        c = graph[s][n]
        dist = tsp(graph, visited | set([s]), n) + c
        if min_d is None or min_d > dist:
            min_d = dist
    return min_d


def solve(r, A, B, C):
    graph = construct_graph(A, B, C)
    d = dijkstra_all(graph, r)
    minimum_dist = tsp_dist(d)
    return minimum_dist


def main():
    N, M, R = list(map(int, input().split(' ')))
    r = list(map(int, input().split(' ')))
    A = []
    B = []
    C = []
    for i in range(M):
        a, b, c = list(map(int, input().split(' ')))
        A.append(a)
        B.append(b)
        C.append(c)
    print(solve(r, A, B, C))

if __name__ == '__main__':
    main()

Solution (Python):
from scipy.sparse.csgraph import dijkstra

n, m, r = map(int,input().split())
rs = list(map(int, input().split()))
edge = [[0]*n for i in range(n)]
for i in range(m):
    a, b, c = list(map(int, input().split()))
    a, b = a-1, b-1
    edge[a][b] = c
    edge[b][a] = c
dist = dijkstra(edge, directed=False, indices=[i for i in range(n)])

from itertools import permutations
ans = float("inf")
    
for v in permutations(rs, len(rs)):
    dist_tmp = 0
    for i in range(r-1):
        dist_tmp += dist[v[i]-1][v[i+1]-1]
    ans = min(ans, int(dist_tmp))
print(ans)

Solution (Python):
from scipy.sparse.csgraph import floyd_warshall

n, m, r = map(int,input().split())
rs = list(map(int, input().split()))
edge = [[0]*n for i in range(n)]
for i in range(m):
    a, b, c = list(map(int, input().split()))
    a, b = a-1, b-1
    edge[a][b] = c
    edge[b][a] = c
dist = floyd_warshall(edge, directed=False)

from itertools import permutations
ans = float("inf")
    
for v in permutations(rs, len(rs)):
    dist_tmp = 0
    for i in range(r-1):
        dist_tmp += dist[v[i]-1][v[i+1]-1]
    ans = min(ans, int(dist_tmp))
print(ans)

Solution (Python):
inf = 10**15
import itertools
n,m,r = map(int,input().split())
city = list(map(int,input().split()))


dist = [[inf for i in range(n)] for i in range(n)]


for i in range(m):
    ak,bk,ck = map(int,input().split())
    dist[ak-1][bk-1]  =ck
    dist[bk-1][ak-1]  =ck

for a in range(n):
    for b in range(n):
        for c in range(n):
            dist[b][c] = min(dist[b][c],dist[b][a]+dist[a][c])



ans = inf
for v in itertools.permutations(city):
    cost = 0
    for i in range(len(v)-1):
        cost += dist[v[i]-1][v[i+1]-1]
    
    ans = min(ans,cost)

print(ans)

Solution (Python):
from scipy.sparse.csgraph import floyd_warshall
import itertools
n,m,r = map(int,input().split())
L = list(map(int,input().split()))
d = [[float("inf")]*n for i in range(n)]
for i in range(n):
    d[i][i] = 0
for i in range(m):
    a,b,l = map(int,input().split())
    d[a-1][b-1] = l
    d[b-1][a-1] = l
d = floyd_warshall(d)
ans = float('inf')
seq = []
for i in range(r):
  seq.append(i)
K = list(itertools.permutations(seq))
for i in range(len(K)):
  cur = 0
  for j in range(1,r):
    p = L[K[i][j-1]]-1
    q = L[K[i][j]]-1
    cur += d[p][q]
  if cur != float('inf'):
    if cur <= ans:
      ans = cur
print(int(ans))

Solution (Python):
def solve():
        from itertools import permutations
        N, M, R = map(int, input().split())
        rs = map(lambda x: int(x) - 1, input().split())
        dist, ans = [[float("inf") for _ in range(N)] for _ in range(N)], float("inf")
        for _ in range(M):
            v1, v2, d = map(int, input().split())
            dist[v1-1][v2-1] = dist[v2-1][v1-1] = d
        for i in range(N):
            dist[i][i] = 0
        for k in range(N):
            for i in range(N):
                for j in range(N):
                    if dist[i][j] > dist[i][k] + dist[k][j]:
                        dist[i][j] = dist[i][k] + dist[k][j]
        for r in permutations(rs):
            t = 0
            for i in range(R - 1):
                t += dist[r[i]][r[i + 1]]
            ans = min(t, ans)
        print(ans)

if __name__ == "__main__":
    solve()

Solution (Python):
if __name__ == "__main__":
    from itertools import permutations
    N, M, R = map(int, input().split())
    rs = map(lambda x: int(x) - 1, input().split())
    dist = [[10**9 for _ in range(N)] for _ in range(N)]
    for _ in range(M):
        v1, v2, d = map(int, input().split())
        dist[v1-1][v2-1] = dist[v2-1][v1-1] = d
    for i in range(N):
        dist[i][i] = 0
    for k in range(N):
        for i in range(N):
            for j in range(N):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
    ans = 10**9
    for r in permutations(rs):
        t = 0
        for i in range(R-1):
            t += dist[r[i]][r[i+1]]
            if t > 10**9:
                break
        ans = min(t, ans)
    print(ans)