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):
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)

Solution (Python):
import itertools

INF = float("inf")


def main():
    N, M, R = map(int, input().split())
    r = list(map(int, input().split()))
    path = [[INF]*(N+1) for _ in range(N+1)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        path[A][B] = C
        path[B][A] = C
    for i in range(1, N+1):
        path[i][i] = 0
    for i in range(1, N+1):
        for j in range(1, N+1):
            for k in range(1, N+1):
                path[j][k] = min(path[j][k], path[j][i] + path[i][k])
    ans = INF
    for p in itertools.permutations(r):
        cost = 0
        for i in range(R-1):
            cost += path[p[i]][p[i+1]]
        ans = min(ans, cost)
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):

from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = SR()
    return l
mod = 1000000007






"""
n = I()
d = defaultdict(int)
for i in range(n):
    a = I()
    d[a] ^= 1
d = list(d.values())
print(sum(d))
"""

def dfs(n,k,l,a):
    if n == 0:
        a.append(l)
    for i in range(n):
        dfs(n-1,k[:i]+k[i+1:],l+[k[i]],a)
n,m,R = LI()
r = LI()
f = [i for i in range(n)]
for i in range(R):
    r[i] -= 1
v = [[float("inf") for j in range(n)] for i in range(n)]
for i in range(n):
    v[i][i] = 0
for i in range(m):
    a,b,c = LI()
    a -= 1
    b -= 1
    v[a][b] = c
    v[b][a] = c
for k in range(n):
    for i in range(n):
        for j in range(n):
            v[i][j] = min(v[i][j],v[i][k]+v[k][j])
l = []
dfs(R,r,[],l)
ans = float("inf")
for k in l:
    d = 0
    for i in range(R-1):
        d += v[k[i]][k[i+1]]
    ans = min(ans,d)
print(ans)

Solution (Python):
from itertools import permutations
import heapq
import sys

INF = 2 ** sys.int_info.bits_per_digit

def warshall(N, ABCs):
    dists = [[INF for _ in range(N)] for __ in range(N)]
    for i in range(N):
        dists[i][i] = 0

    for a, b, c in ABCs:
        dists[a - 1][b - 1] = c
        dists[b - 1][a - 1] = c

    for s in range(N):
        for e in range(N):
            for i in range(N):
                dists[s][e] = min(dists[s][e], dists[s][i] + dists[i][e])
    return dists


def dijkstra(s, e, N, ABCs):
    adjlist = [[] for _ in range(N)]
    for a, b, c in ABCs:
        adjlist[a - 1].append((b, c))
        adjlist[b - 1].append((a, c))

    q = [(0, s)]
    while len(q):
        d, i = heapq.heappop(q)
        if i == e:
            return d
        for nexti, nextd in adjlist[i - 1]:
            heapq.heappush(q, (d + nextd, nexti))
    return None


def dense_dijkstra(s, e, N, ABCs):
    distsmap = [[-1 for _ in range(N)] for __ in range(N)]
    for a, b, c in ABCs:
        distsmap[a - 1][b - 1] = c
        distsmap[b - 1][a - 1] = c

    dists = [INF for _ in range(N)]
    visited = [False for _ in range(N)]
    dists[s - 1] = 0

    while True:
        minW, index = min([(dists[i], i) for i in range(N) if not visited[i]])
        visited[index] = True
        if minW == INF:
            return -1
        if index + 1 == e:
            return minW
        for rindex, w in enumerate(distsmap[index]):
            if w == -1:
                continue
            dists[rindex] = min(dists[rindex], minW + w)













def solve(N, M, R, Rs, ABCs):
    dists = [[-1 for _ in range(N)] for __ in range(N)]
    ans = INF
    for way in permutations(Rs):
        tans = 0
        for s, e in zip(way, way[1:]):
            if dists[s - 1][e - 1] == -1:
                d = dense_dijkstra(s, e, N, ABCs)
                dists[s - 1][e - 1] = d
                dists[e - 1][s - 1] = d
            else:
                d = dists[s - 1][e - 1]
            tans += d
        ans = min(ans, tans)

    return ans

if __name__ == "__main__":
    N, M, R = tuple(map(int, input().split(" ")))
    Rs = list(map(int, input().split(" ")))
    ABCs = [tuple(map(int, input().split(" "))) for _ in range(M)]
    print(solve(N, M, R, Rs, ABCs))

Solution (Python):
from itertools import permutations
import heapq

INF = 100000 * 200 * 10

def warshall(N, ABCs):
    dists = [[INF for _ in range(N)] for __ in range(N)]
    for i in range(N):
        dists[i][i] = 0

    for a, b, c in ABCs:
        dists[a - 1][b - 1] = c
        dists[b - 1][a - 1] = c

    for s in range(N):
        for e in range(N):
            for i in range(N):
                dists[s][e] = min(dists[s][e], dists[s][i] + dists[i][e])
    return dists


def dijkstra(s, e, N, ABCs):
    adjlist = [[] for _ in range(N)]
    for a, b, c in ABCs:
        adjlist[a - 1].append((b, c))
        adjlist[b - 1].append((a, c))

    q = [(0, s)]
    while len(q):
        d, i = heapq.heappop(q)
        if i == e:
            return d
        for nexti, nextd in adjlist[i - 1]:
            heapq.heappush(q, (d + nextd, nexti))
    return None


def dense_dijkstra(s, e, N, ABCs):
    distsmap = [[-1 for _ in range(N)] for __ in range(N)]
    for a, b, c in ABCs:
        distsmap[a - 1][b - 1] = c
        distsmap[b - 1][a - 1] = c

    dists = [INF for _ in range(N)]
    visited = [False for _ in range(N)]
    dists[s - 1] = 0

    while True:
        minW, index = min([(dists[i], i) for i in range(N) if not visited[i]])
        visited[index] = True
        if minW == INF:
            return -1
        if index + 1 == e:
            return minW
        for rindex, w in enumerate(distsmap[index]):
            if w == -1:
                continue
            dists[rindex] = min(dists[rindex], minW + w)


def solve(N, M, R, Rs, ABCs):
    dists = [[-1 for _ in range(N)] for __ in range(N)]
    ans = INF
    for way in permutations(Rs):
        tans = 0
        for s, e in zip(way, way[1:]):
            if dists[s - 1][e - 1] == -1:
                d = dense_dijkstra(s, e, N, ABCs)
                dists[s - 1][e - 1] = d
                dists[e - 1][s - 1] = d
            else:
                d = dists[s - 1][e - 1]
            tans += d
        ans = min(ans, tans)

    return ans

if __name__ == "__main__":
    N, M, R = tuple(map(int, input().split(" ")))
    Rs = list(map(int, input().split(" ")))
    ABCs = [tuple(map(int, input().split(" "))) for _ in range(M)]
    print(solve(N, M, R, Rs, ABCs))

Solution (Python):
def solve():
    from itertools import permutations
    n,m,R=map(int,input().split())
    r=map(int,input().split())
    d=[[10**18]*n for _ in range(n)]
    for i in range(m):
        a,b,c=map(int,input().split())
        d[a-1][b-1]=c
        d[b-1][a-1]=c
    for i in range(n):
        d[i][i]=0
    for k in range(n):
        for i in range(n):
            for j in range(n):
                t=d[i][k]+d[k][j]
                if t<d[i][j]:
                    d[i][j]=t
    m=10**18
    for e in permutations(r):
        t=0
        for i,j in zip(e,e[1:]):
            t+=d[i-1][j-1]
        if t<m:
            m=t
    print(m)
if __name__=='__main__':
    solve()

Solution (Python):
from itertools import*
n,m,R=map(int,input().split())
r=map(int,input().split())
d=[[10**18]*n for _ in range(n)]
for i in range(m):
    a,b,c=map(int,input().split())
    d[a-1][b-1]=c
    d[b-1][a-1]=c
for i in range(n):
    d[i][i]=0
for k in range(n):
    for i in range(n):
        for j in range(n):
            d[i][j]=min(d[i][j],d[i][k]+d[k][j])
m=10**18
for e in permutations(r):
    t=0
    for i,j in zip(e,e[1:]):
        t+=d[i-1][j-1]
    m=min(m,t)
print(m)

Solution (Python):
import itertools

n, m, r = map(int, input().split())
rlist = list(map(int, input().split()))
dist = [[-1 for _ in range(n)] for _ in range(n)]
for i in range(n):
  dist[i][i] = 0
abcl = []
for _ in range(m):
  a, b, c = map(int, input().split())
  dist[a-1][b-1] = c
  dist[b-1][a-1] = c

for k in range(0, n):
  for i in range(0, n):
    for j in range(0, n):
      if dist[i][k] != -1 and dist[k][j] != -1:
        if dist[i][j] == -1:
          dist[i][j] = dist[i][k] + dist[k][j]
        elif dist[i][j] > dist[i][k] + dist[k][j]:
          dist[i][j] = dist[i][k] + dist[k][j]

ans = pow(10, 15)
minp = None
for rperm in itertools.permutations(rlist):
  tmp = 0
  tmpp = [rperm[0]-1]
  for pr, nr in zip(rperm, rperm[1:]):
    tmp += dist[pr-1][nr-1]
    tmpp.append(nr-1)
  if ans > tmp:
    ans = tmp
    minp = tmpp
print(ans)

Solution (Python):
N,M,R = map(int, input().split())
r = list(map(int, input().split()))
ABC = [ [int(j) for j in input().split()] for _ in range(M)]

inf = float("inf")
costmap =   [  [inf] * (N+1)  for _ in range(N+1)] 

for i in range(M):
    a,b,c = ABC[i]

    costmap[a][b] = c
    costmap[b][a] = c


for k in range(1, N+1):
    for i in range(1, N+1):
        for j in range(1, N+1):
            if costmap[i][j] > costmap[i][k] + costmap[k][j]:
                c = costmap[i][k] + costmap[k][j]
                costmap[i][j] = c
                costmap[j][i] = c

from itertools import permutations
ans = inf
for itr in permutations( [x for x in range(R)]):
    tmp = 0
    now = r[itr[0]]
    for n in itr[1:]:
        tmp += costmap[now][ r[n] ]
        now = r[n]
    ans = min(ans, tmp)
print(ans)

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


def warshall_floyd(dist,n):
    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]

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

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

for a,b,c in info:
    a -= 1; b -= 1
    dist[a][b] = c
    dist[b][a] = c

warshall_floyd(dist,N)

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

print(ans)

Solution (Python):
import itertools
inf = float("inf")
n,m,r = map(int,input().split())
ra = list(map(int,input().split()))
dist = [[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 a in range(n):
    for b in range(n):
        for c in range(n):
            dist[b-1][c-1] = min(dist[b-1][c-1],dist[b-1][a-1]+dist[a-1][c-1])



    

ans = inf
for p in itertools.permutations(ra):
    subt = 0
    for i in range(r-1):
        subt += dist[p[i]-1][p[i+1]-1]
    if subt < ans:
        ans = subt
print(ans)

Solution (Python):
import sys
import itertools
input = sys.stdin.readline
def warshall_floyd(d):
    
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

n,w,R = map(int,input().split())
r = list(map(int,input().split()))
d = [[float("inf") for i in range(n)] for i in range(n)] 

for i in range(w):
    x,y,z = map(int,input().split())
    d[x-1][y-1] = z
    d[y-1][x-1] = z
for i in range(n):
    d[i][i] = 0 
for i in range(R):
    r[i] -= 1
d = warshall_floyd(d)

res = float("inf")
for v in itertools.permutations(r,R):
    sumd = 0
    for j in range(1,R):
        sumd += d[v[j-1]][v[j]]
    res = min(res,sumd)
print(res)

Solution (Python):
from itertools import permutations

N,M,R = map(int, input().split())
r = map(int, input().split())
r = [ri-1 for ri in r]
d_matrx = [[float('inf')]*N for _ in range(N)]
for _ in range(M):
    a,b,c = map(int, input().split())
    d_matrx[a-1][b-1] = c
    d_matrx[b-1][a-1] = c

def warshall_floyd(v_count: int, matrix: list) -> list:
    """ ワーシャルフロイド　
    :param v_count: 頂点数
    :param matrix:  隣接行列(到達不能はfloat("inf"))
    """
    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

warshall_floyd(N, d_matrx)
ans = float('inf')
for p in permutations(r):
    cond = 0
    cur = p[0]
    for nex in p[1:]:
        cond += d_matrx[cur][nex]
        cur = nex
    ans = min(ans, cond)
print(ans)

Solution (Python):
from itertools import permutations

N,M,R=map(int,input().split())
*r,=map(int,input().split())
inf=float("inf")
d=[[inf]*N for _ in range(N)]

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

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

ans=inf
for i in permutations(r):
    v=0
    for j in range(R-1):
        v+=d[i[j]-1][i[j+1]-1]
    ans=min(ans,v)

print(ans)

Solution (Python):
def di(cost,start,goal,numV,ii):
  d = [float("inf")]*numV
  used = [False]*numV
  d[start] = 0
  while True:
    v = -1
    for i in range(numV):
      if (not used[i]) and (v ==-1 or d[i]<d[v]):
        v = i
    if v == -1:
      break 
    used[v] = True
    for i in range(numV):
      d[i] =min(d[i],d[v]+cost[v][i])
  
  for i in range(len(goal)):
    shortest_matrix[ii][i] = d[goal[i]]
  return

      
n,m,r = map(int,input().split())
li_r = list(map(int,input().split()))
for i in range(len(li_r)):
  li_r[i] = li_r[i]-1

matrix = [[float("inf")]*n for i in range(n)]
shortest_matrix=[[0]*r for i in range(r)]

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







for iii in range(len(li_r)):  
  di(matrix,li_r[iii],li_r,n,iii)

import itertools 
base = [i for i in range(len(li_r))]
li =[]
for i in itertools.permutations(base):
   li.append(i)

ans = float("inf")
for chiten in li:
  tmp_ans = 0
  for j in range(1,len(chiten)):
    tmp_ans = tmp_ans +shortest_matrix[chiten[j]][chiten[j-1]]
  ans = min(ans,tmp_ans)
print(ans)

Solution (Python):
from itertools import permutations
class Solve():
    def __init__(self):
        self.N, self.M, self.R = map(int, input().split())
        self.r = list(map(int, input().split()))
        self.route = [[float('inf') for _ in range(self.N)] for _ in range(self.N)]
        for _ in range(self.M):
            a, b, c = map(int, input().split())
            self.route[a - 1][b - 1] = c
            self.route[b - 1][a - 1] = c
        for i in range(self.N):
            self.route[i][i] = 0

    def WarshallFloid(self):
        for k in range(self.N):
            for i in range(self.N):
                for j in range(self.N):
                    if self.route[i][j] > self.route[i][k] + self.route[k][j]:
                        self.route[i][j] = self.route[i][k] + self.route[k][j]

    def execute(self):
        self.WarshallFloid()
        ans = float('inf')
        checked = set()
        for path in permutations(self.r):
            if tuple(reversed(path)) in checked:
                continue
            checked.add(tuple(reversed(path)))
            temp = 0
            for i in range(self.R - 1):
                temp += self.route[path[i] - 1][path[i + 1] - 1]
            ans = min(ans, temp)
        print(ans)


if __name__ == '__main__':
    Solve().execute()

Solution (Python):
import itertools
N, M, R = map(int, input().split())
r = tuple(map(lambda n: int(n)-1, input().split()))
inf = float("inf")
vertices = [[inf]*N for _ in [0]*N]
for _ in [0]*M:
    a, b, c = map(int, input().split())
    vertices[a-1][b-1] = c
    vertices[b-1][a-1] = c

for k in range(N):
    for i in range(N):
        c2 = vertices[i][k]
        for j, (c1, c3) in enumerate(zip(vertices[i], vertices[k])):
            vertices[i][j] = c1 if c1 < c2+c3 else c2+c3

ans = inf

for p in itertools.permutations(r):
    subt = 0
    for i in range(R-1):
        subt += vertices[p[i]][p[i+1]]
    if subt < ans:
        ans = subt

print(ans)

Solution (Python):
from collections import defaultdict
import heapq as hq
from itertools import permutations
def dijkstra(E, D, start,W):
    q = []
    V = [-1]*N
    V[start] = 0
    
    
    
    
    
    for e in E[start]:
        if V[e] == -1:
            hq.heappush(q, (D[start, e],e))
    
    while q:
        d, v = hq.heappop(q)
        if V[v] >= 0:
            continue
        V[v] = d
        for e in E[v]:
            if V[e] == -1:
                hq.heappush(q, (D[v,e]+d, e))
    return V
N, M, r = map( int, input().split())
R = list( map( int, input().split()))
d = defaultdict( int)
E = [ [] for _ in range(N)]
for _ in range(M):
    a, b, c = map( int, input().split())
    a, b = a-1, b-1
    d[(a,b)] = d[(b,a)] = c
    E[a].append(b)
    E[b].append(a)
W = [ [-1]*N for i in range(N)]


    
for i in range(r):
    W[R[i]-1] = dijkstra(E,d,R[i]-1,W)

ans = 10**9
for P in permutations( range(r)):
    now = R[P[0]]-1
    cans = 0
    for i in range(1,r):
        cans += W[now][R[P[i]]-1]
        now = R[P[i]]-1
    if cans < ans:
        ans = cans
print( ans)

Solution (Python):
from collections import defaultdict
import heapq as hq
from itertools import permutations
def dijkstra(E, D, start,W):
    q = []
    V = [-1]*N
    V[start] = 0
    
    
    
    
    
    for e in E[start]:
        if V[e] == -1:
            hq.heappush(q, (D[start, e],e))
    
    while q:
        d, v = hq.heappop(q)
        if V[v] >= 0:
            continue
        V[v] = d
        for e in E[v]:
            if V[e] == -1:
                hq.heappush(q, (D[v,e]+d, e))
    return V
N, M, r = map( int, input().split())
R = list( map( int, input().split()))
d = defaultdict( int)
E = [ [] for _ in range(N)]
for _ in range(M):
    a, b, c = map( int, input().split())
    a, b = a-1, b-1
    d[(a,b)] = d[(b,a)] = c
    E[a].append(b)
    E[b].append(a)
W = [ [-1]*N for i in range(N)]


    
for i in range(r):
    W[R[i]-1] = dijkstra(E,d,R[i]-1,W)

ans = 10**9
for P in permutations( range(r)):
    now = R[P[0]]-1
    cans = 0
    for i in range(1,r):
        cans += W[now][R[P[i]]-1]
        now = R[P[i]]-1
    if cans < ans:
        ans = cans
print( ans)

Solution (Python):
import heapq
import itertools
n,m,R=map(int,input().split())
r=list(map(int,input().split()))
edges=[[] for _ in range(n)]
for _ in range(m):
    a,b,c = map(int, input().split())
    a,b=a-1,b-1
    edges[a].append((b, c))
    edges[b].append((a, c))

def dijkstra(x,route):
    d=[float('inf')]*n
    d[x]=0
    visited={x}
    hq=[(0,x)]
    while hq:
        u=heapq.heappop(hq)[1]
        visited.add(u)
        for node, cost in route[u]:
            if (node not in visited) and d[node]>d[u]+cost:
                d[node]=d[u]+cost
                heapq.heappush(hq,(d[node],node))
    return d
dist=[[] for _ in range(R)]
for i in range(R):
    start=r[i]-1
    dist[i]=dijkstra(start,edges)
ans=float("inf")
t=itertools.permutations(r)
for i in t:
    d=0
    start=i[0]
    for end in i[1:]:
        d+=dist[r.index(start)][end-1]
        start=end
    ans=min(ans,d)
print(ans)

Solution (Python):
n, m, r = list(map(int, input().split()))
rs = list(map(int, input().split()))

import numpy as np
dists = np.ones((n + 1, n + 1)) * float('inf')
for _ in range(m):
    a, b, c = list(map(int, input().split()))
    dists[a, b] = dists[b, a] = c
for i in range(1, n + 1):
    dists[i, i] = 0

from itertools import permutations
for i in range(1, 1 + n):
    dists = np.minimum(dists, dists[i: i + 1] + dists[:, i: i + 1])

ans = float('inf')
for path in permutations(rs):
    val = sum(dists[i, j] for i, j in zip(path, path[1:]))
    val = int(val)
    if val < ans:
        ans = val

print(ans)

Solution (Python):
n, m, r = list(map(int, input().split()))
rs = list(map(int, input().split()))

import numpy as np
dists = np.ones((n + 1, n + 1)) * float('inf')
for _ in range(m):
    a, b, c = list(map(int, input().split()))
    dists[a, b] = dists[b, a] = c
for i in range(1, n + 1):
    dists[i, i] = 0

from itertools import product, permutations
for i, j in product(range(1, 1 + n), repeat=2):
    dists[j] = np.minimum(dists[j], dists[i] + dists[j, i])

ans = float('inf')
for path in permutations(rs):
    val = sum(dists[i, j] for i, j in zip(path, path[1:]))
    val = int(val)
    if val < ans:
        ans = val

print(ans)

Solution (Python):
n, m, r = list(map(int, input().split()))
rs = list(map(int, input().split()))

import numpy as np
dists = np.ones((n + 1, n + 1)) * float('inf')
for _ in range(m):
    a, b, c = list(map(int, input().split()))
    dists[a, b] = dists[b, a] = c
for i in range(1, n + 1):
    dists[i, i] = 0

from itertools import product, permutations
for i, k in product(range(1, 1 + n), repeat=2):
    dists[:, k] = np.minimum(dists[:, k], dists[:, i] + dists[i, k])

ans = float('inf')
for path in permutations(rs):
    val = sum(dists[i, j] for i, j in zip(path, path[1:]))
    val = int(val)
    if val < ans:
        ans = val

print(ans)

Solution (Python):
from heapq import heappush, heappop
INF = 10 ** 20
n, m, r = map(int, input().split())
rList = list(map(int, input().split()))

edges = [[] for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    a, b = a - 1, b - 1
    edges[a].append((b, c))
    edges[b].append((a, c))

def dijkstra(start):
    dist = [INF] * n
    dist[start] = 0
    que = []
    heappush(que, (0, start))
    while que:
        time, node = heappop(que)
        for to, cost in edges[node]:
            newTime = time + cost
            if newTime < dist[to]:
                dist[to] = newTime
                heappush(que, (newTime, to))
    return dist

rDist = [[] for _ in range(r)]
for i in range(r):
    dist = dijkstra(rList[i] - 1)
    rDist[i] = [dist[j - 1] for j in rList]

dic = {}
end = 2 ** r - 1
def minCost(state, pos):
    if (state, pos) in dic:
        return dic[(state, pos)]
    if state == end:
        return 0

    mask = 1
    ret = INF
    for to in range(r):
        if state & mask:
            mask <<= 1
            continue

        newState = state | mask
        ret = min(ret, rDist[pos][to] + minCost(newState, to))
        mask <<= 1

    dic[(state, pos)] = ret
    return ret

print(min([minCost(2 ** i, i) for i in range(r)]))

Solution (Python):
from itertools import permutations
N, M, R = map(int, input().split())
r = list(map(int, input().split()))
G = [[10**18]*(N+1) for _ in range(N+1)]
for _ in range(M):
    a, b, c = map(int, input().split())
    G[a][b] = c
    G[b][a] = c

for k in range(1, N+1):
    for i in range(1, N+1):
        for j in range(1, N+1):
            if G[i][k]+G[k][j] < G[i][j]:
                G[i][j] = G[i][k] + G[k][j]


ans = 10**18
for elem in permutations(r):
    res = 0
    for i in range(R-1):
        res += G[elem[i]][elem[i+1]]
    ans = min(ans, res)
print(ans)

Solution (Python):
import itertools
n, m, R = map(int, input().split())
r = list(map(int, input().split()))
dis = [[float("inf") for _ in range(n)] for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    dis[a - 1][b - 1] = c
    dis[b - 1][a - 1] = c


def war(dis):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if dis[i][j] > dis[i][k] + dis[k][j]:
                    dis[i][j] = dis[i][k] + dis[k][j]
    return dis


dis = war(dis)
ans = float('inf')
it = itertools.permutations(r)
for l in it:
    tmp = 0
    for u, v in zip(l, l[1:]):
        tmp += dis[u-1][v-1]
        if tmp > ans:
            break
    ans = min(ans, tmp)

print(ans)

Solution (Python):
import itertools
n, m, R = map(int, input().split())
r = list(map(int, input().split()))
dis = [[0 for _ in range(n)] for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    dis[a - 1][b - 1] = c
    dis[b - 1][a - 1] = c

def war(dis):
    size = len(dis)
    
    for i in range(size):
        for j in range(size):
            if i != j and dis[i][j] == 0:
                dis[i][j] = float("inf")
    for k in range(size):
        for i in range(size):
            for j in range(size):
                if dis[i][j] > dis[i][k] + dis[k][j]:
                    dis[i][j] = dis[i][k] + dis[k][j]
    return dis
dis = war(dis)
_min = float("inf")
it = itertools.permutations(r)
for iterR in it:
    _dis = 0
    start = iterR[0] - 1
    for end in iterR[1:]:
        _dis += dis[start][end - 1]
        start = end - 1
    _min = min(_min, _dis)
print(_min)

Solution (Python):
def washall_floyd(graph):
    num_v = len(graph)
    for k in range(num_v):
        for i in range(num_v):
            for j in range(num_v):
                if graph[i][j] > graph[i][k] + graph[k][j]:
                    graph[i][j] = graph[i][k] + graph[k][j]
    return graph


n, m, r = map(int, input().split())
r_list = list(map(int, input().split()))
graph = [[float("inf") for _ in range(n)] for _ in range(n)]
for i in range(m):
    a, b, c = map(int, input().split())
    graph[a - 1][b - 1] = c
    graph[b - 1][a - 1] = c

graph = washall_floyd(graph)
result = float("inf")
import itertools
permi = itertools.permutations(r_list)
for per in permi:
    r = 0
    start = per[0] - 1
    for p in per[1:]:
        end = p - 1
        r += graph[start][end]
        start = p - 1
    result = min(r, result)
print(result)

Solution (Python):
from itertools import permutations
import sys


input = sys.stdin.readline


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

dest = [x-1 for x in map(int, input().split())]


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


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


ans = inf
for l in permutations(dest):
    tmp = 0
    for u, v in zip(l, l[1:]):
        tmp += mat[u][v]
    ans = min(ans, tmp)

print(ans)

Solution (Python):
import itertools
n, m, R = map(int, input().split())
r = list(map(int, input().split()))
dis = [[float("inf") for _ in range(n)] for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    dis[a - 1][b - 1] = c
    dis[b - 1][a - 1] = c

def war(dis):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if dis[i][j] > dis[i][k] + dis[k][j]:
                    dis[i][j] = dis[i][k] + dis[k][j]
    return dis
dis = war(dis)
_min = float("inf")
it = itertools.permutations(r)
for iterR in it:
    _dis = 0
    start = iterR[0] - 1
    for end in iterR[1:]:
        _dis += dis[start][end - 1]
        start = end - 1
    _min = min(_min, _dis)
print(_min)

Solution (Python):


import sys
import heapq
import itertools
from collections import defaultdict

INF = float('inf')
MOD = 10 ** 9 + 7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()


def dijkstra(start: int, size: int, graph: dict) -> list:
    costs = [INF] * size
    costs[start] = 0
    visited = set()
    hp = []
    heapq.heappush(hp, (0, start))
    while hp:
        hc, hv = heapq.heappop(hp)
        if hv in visited:
            continue
        for to, move_cost in graph[hv]:
            if hc + move_cost >= costs[to]:
                continue
            costs[to] = hc + move_cost
            heapq.heappush(hp, (costs[to], to))
        visited.add(hv)

    return costs


n, m, r = LI()
R = LI_()

G = defaultdict(list)
for i in range(m):
    a, b, c = LI()
    a -= 1
    b -= 1
    G[a].append((b, c))
    G[b].append((a, c))

C = {}
for ri in R:

    C[ri] = dijkstra(ri, n, G)

ans = INF
for root in itertools.permutations(R):
    tmp = 0
    for i in range(r - 1):
        tmp += C[root[i]][root[i + 1]]
    ans = min(ans, tmp)

print(ans)

Solution (Python):


import sys
import heapq
import itertools
from collections import defaultdict

INF = float('inf')
MOD = 10 ** 9 + 7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()


def dijkstra(start: int, size: int, graph: dict) -> list:
    costs = [INF] * size
    costs[start] = 0
    hp = []
    heapq.heappush(hp, (0, start))
    while hp:
        hc, hv = heapq.heappop(hp)
        for to, move_cost in graph[hv]:
            if hc + move_cost >= costs[to]:
                continue
            costs[to] = hc + move_cost
            heapq.heappush(hp, (costs[to], to))

    return costs


n, m, r = LI()
R = LI_()

G = defaultdict(list)
for i in range(m):
    a, b, c = LI()
    a -= 1
    b -= 1
    G[a].append((b, c))
    G[b].append((a, c))

C = {}
for ri in R:
    C[ri] = dijkstra(ri, n, G)

ans = INF
for root in itertools.permutations(R):
    tmp = 0
    for i in range(r - 1):
        tmp += C[root[i]][root[i + 1]]
    ans = min(ans, tmp)

print(ans)