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

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

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

for i in range(R):
    r[i]-=1

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

for rr in itertools.permutations(r,R):
    t_sum=0
    for j in range(1,R):
        t_sum+=mat[rr[j-1]][rr[j]]
    ans=min(ans,t_sum)
print(int(ans))

Solution (Python):
N,M,C=[int(x) for x in str(input()).split()]
r=[int(x) for x in str(input()).split()]
ABC=[[0 for i in range(4)]]

dis=[[1000000000000 for i in range(N+1)]]

for i in range(N):
  dis.append([1000000000000 for i in range(N+1)])


for i in range(M):
  x=[0]+[int(x) for x in str(input()).split()]
  ABC.append(x)
  dis[x[1]][x[2]]=x[3]
  dis[x[2]][x[1]]=x[3]
  y=[0,x[2],x[1],x[3]]
  ABC.append(y)

for i in range(1,N+1):
  dis[i][i]=0


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


mi=1000000000000
def perm(a,i):
  global mi
  if i==len(a):      

    p=0
    for x in range(len(a)-1):
      p+=dis[a[x]][a[x+1]]

    mi=min(mi,p)


  else:
    for j in range(i,len(a)):
      a[i],a[j]=a[j],a[i]
      perm(a,i+1)
      a[i],a[j]=a[j],a[i]


perm(r,0)

print(mi)

Solution (Python):

from scipy.sparse.csgraph import floyd_warshall
from itertools import permutations

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

inf = 10**18
dist = [[inf]*N for _ in range(N)]
for i in range(M):
    A, B, C = map(int, input().split())
    dist[A-1][B-1] = dist[B-1][A-1] = C

dist = floyd_warshall(dist)

ans = inf
for rr in permutations(r):
    cost = 0
    for i in range(R-1):
        cost += dist[rr[i]-1][rr[i+1]-1]
    ans = min(ans, cost)
print(int(ans))

Solution (Python):

from scipy.sparse.csgraph import floyd_warshall
from itertools import permutations

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

inf = 10**18
dist = [[inf]*N for _ in range(N)]
for i in range(M):
    A, B, C = map(int, input().split())
    dist[A-1][B-1] = dist[B-1][A-1] = C

dist = floyd_warshall(dist)

ans = inf
for rr in permutations(r):
    cost = 0
    for i in range(R-1):
        cost += dist[rr[i]-1][rr[i+1]-1]
    if cost < ans:
        ans = cost
print(int(ans))

Solution (Python):
import itertools
import numpy as np
import sys
input = sys.stdin.buffer.readline

def main():
    N,M,R = map(int,input().split())
    r = list(map(int,input().split()))
    INF = float('INF')
    root = [[INF for _ in range(N)] for _ in range(N)]
    for i in range(N):
        root[i][i] = 0
    for i in range(M):
        A,B,C = map(int,input().split())
        root[A-1][B-1] = C
        root[B-1][A-1] = C
    
    for i in range(N):
        for j in range(N):
            for k in range(N):
                if root[j][k] > root[j][i]+root[i][k]:
                    root[j][k] = root[j][i]+root[i][k]
                
    ans = INF
    for i in itertools.permutations(r):
        L = 0
        for j in range(R-1):
            L += root[i[j]-1][i[j+1]-1]
        ans = min(ans,L)
                
    print(ans)
    
if __name__ == "__main__":
    main()

Solution (Python):
from itertools import permutations as perm

def warshall(d, n):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if d[i][k] + d[k][j] < d[i][j]:
                    d[i][j] = d[i][k] + d[k][j]

n,m,r = map(int, input().split())
rr = [i-1 for i in map(int, input().split())]

inf = float('INF')
route = [[inf for j in range(n)] for i in range(n)]
for _ in range(m):
    a,b,c = map(int, input().split())
    route[a-1][b-1] = route[b-1][a-1] = c

warshall(route, n)

ans = inf
for tmp in perm(rr):
    cost = 0
    for i in range(r-1):
        cost += route[tmp[i]][tmp[i+1]]
    if cost < ans:
        ans = cost
print(int(ans))

Solution (Python):
from itertools import permutations as perm
from scipy.sparse.csgraph import dijkstra as di

def warshall(d, n):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if d[i][k] + d[k][j] < d[i][j]:
                    d[i][j] = d[i][k] + d[k][j]

n,m,r = map(int, input().split())
rr = [i-1 for i in map(int, input().split())]

inf = float('INF')
route = [[0 for j in range(n)] for i in range(n)]
for _ in range(m):
    a,b,c = map(int, input().split())
    route[a-1][b-1] = route[b-1][a-1] = c

route = di(route, n)

ans = inf
for tmp in perm(rr):
    cost = 0
    for i in range(r-1):
        cost += route[tmp[i]][tmp[i+1]]
    if cost < ans:
        ans = cost
print(int(ans))

Solution (Python):
import itertools

n,m,r_ = map(int, input().split( ))

r = list(map(int, input().split( )))
for i in range(r_):
  	r[i] -=1
d = [[10**10 for _ in range(n)] for i in range(n)]

for i in range(m):
    ai,bi,ci = map(int, input().split( ))
    ai-=1
    bi-=1
    d[ai][bi] = d[bi][ai] = ci

for k in range(n):
    for i in range(n):
        for j in range(n):
            d[i][j] = min(d[i][k]+d[k][j],d[i][j])
ans= 10**10
for l in itertools.permutations(r,r_):
    tmp = 0
    for i in range(r_-1):
        tmp += d[l[i]][l[i+1]]
    ans = min(ans, tmp)

print(ans)

Solution (Python):
from itertools import permutations

from scipy.sparse import csr_matrix
from scipy.sparse.csgraph._shortest_path import floyd_warshall


def solve():
    N, M, R = map(int, input().split())
    r = list(map(lambda x: int(x)-1, input().split()))
    dist = [[0 for _ in range(N)] for _ in range(N)]
    for _ in range(M):
        A, B, C = map(int, input().split())
        dist[A-1][B-1] = C
        dist[B-1][A-1] = C
    fw = floyd_warshall(csr_matrix(dist))
    
    ans = 10**12
    for visit in permutations(r, R):
        m_sum = 0
        for i in range(R-1):
            m_sum += fw[visit[i]][visit[i+1]]
        ans = min(ans, m_sum)
    print(int(ans))


if __name__ == '__main__':
    solve()

Solution (Python):
import sys,collections as cl,bisect as bs
import itertools
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = 10 ** 15
def l(): 
    return list(map(int,input().split()))
def m(): 
    return map(int,input().split())
def onem(): 
    return int(input())
def s(x): 
    a = []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): 
    return "".join(map(str,x))
def max2(x): 
    return max(map(max,x))
def In(x,a): 
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

def warshall_floyd(n,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,M,r = m()

R = l()

di = [[Max for i in range(N)] for j in range(N)]

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

for i in range(M):
    a,b,c = m()
    a -= 1
    b -= 1
    di[a][b] = c
    di[b][a] = c


di = warshall_floyd(N,di)

Ma = Max


te = list(itertools.permutations(R))
for i in range(len(te)):
    co = 0
    RR = te[i]
    for j in range(r-1):
        co += di[RR[j]-1][RR[j+1]-1]
    Ma = min(co,Ma)
print(Ma)

Solution (Python):
import itertools


def warshal_floyd(d):
    
    global N
    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, M, R = map(int, input().split())  
town = list(map(lambda x: int(x)-1, input().split()))
distant = [[float('inf')]*N for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    distant[a][b] = c
    distant[b][a] = c
for i in range(N):
    distant[i][i] = 0


warshal_floyd(distant)
ans = 10**9
for x in itertools.permutations(town):
    x = list(x)
    now = x[0]
    tmp = 0
    for i in range(1, len(x)):
        tmp += distant[now][x[i]]
        now = x[i]
    ans = min(ans, tmp)
print(int(ans))

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


def warshal_floyd(d):
    
    global N
    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, M, R = map(int, input().split())  
town = list(map(lambda x: int(x)-1, input().split()))
distant = [[float('inf')]*N for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    distant[a][b] = c
    distant[b][a] = c
for i in range(N):
    distant[i][i] = 0
distant = floyd_warshall(distant)


ans = 10**9
for x in itertools.permutations(town):
    x = list(x)
    now = x[0]
    tmp = 0
    for i in range(1, len(x)):
        tmp += distant[now][x[i]]
        now = x[i]
    ans = min(ans, tmp)
print(int(ans))

Solution (Python):

import itertools


def warshal_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, M, R = map(int, input().split())  
town = list(map(lambda x: int(x)-1, input().split()))
distant = [[float('inf')]*N for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    distant[a][b] = c
    distant[b][a] = c
for i in range(N):
    distant[i][i] = 0

warshal_floyd(distant)

ans = 10**9
for x in itertools.permutations(town):
    x = list(x)
    now = x[0]
    tmp = 0
    for i in range(1, len(x)):
        tmp += distant[now][x[i]]
        now = x[i]
    ans = min(ans, tmp)
print(ans)

Solution (Python):


import sys

from scipy.sparse.csgraph import floyd_warshall

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

N, M, R = MAP()
A = [a-1 for a in LIST()]
G = list2d(N, N, INF)
for i in range(M):
    a, b, c = MAP()
    a -= 1; b -= 1
    G[a][b] = c
    G[b][a] = c


wf = floyd_warshall(G)

ans = INF
for r in range(R):
    
    dp = list2d(1<<R, R, INF)
    dp[1<<r][r] = 0
    for bit in range(1, (1<<R)-1):
        for i in range(R):
            if not (bit >> i & 1):
                continue
            for j in range(R):
                if bit >> j & 1:
                    continue
                a, b = A[i], A[j]
                dp[bit|1<<j][j] = min(dp[bit|1<<j][j], dp[bit][i] + int(wf[a,b]))
    ans = min(ans, min(dp[-1]))
print(ans)

Solution (Python):


import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

def warshall_floyd(N: int, graph: list) -> list:
    """ ワーシャルフロイド(頂点数, 隣接行列(0-indexed)) """
    from copy import deepcopy

    res = deepcopy(graph)
    for i in range(N):
        
        res[i][i] = 0
    
    for k in range(N):
        for i in range(N):
            for j in range(N):
                res[i][j] = min(res[i][j], res[i][k] + res[k][j])
    
    for i in range(N):
        if res[i][i] < 0:
            return []
    return res

N, M, R = MAP()
A = [a-1 for a in LIST()]
G = list2d(N, N, INF)
for i in range(M):
    a, b, c = MAP()
    a -= 1; b -= 1
    G[a][b] = c
    G[b][a] = c


wf = warshall_floyd(N, G)

ans = INF
for r in range(R):
    
    dp = list2d(1<<R, R, INF)
    dp[1<<r][r] = 0
    for bit in range(1, (1<<R)-1):
        for i in range(R):
            if not (bit >> i & 1):
                continue
            for j in range(R):
                if bit >> j & 1:
                    continue
                a, b = A[i], A[j]
                dp[bit|1<<j][j] = min(dp[bit|1<<j][j], dp[bit][i] + wf[a][b])
    ans = min(ans, min(dp[-1]))
print(ans)

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

I = np.array(sys.stdin.read().split(), dtype=np.int64)
n, m, R = I[:3]
r = I[3:3+R] - 1
a, b, c = I[3+R:].reshape(-1, 3).T
graph = csr_matrix((c, (a-1, b-1)), shape=(n, n))

def main():
    dist = floyd_warshall(graph, directed=False).astype(np.int64)
    
    perms = np.array(list(permutations(r)))
    res = dist[perms[:, :-1], perms[:, 1:]]
    ans = np.amin(np.sum(res, axis=1))
    return ans

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

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

I = np.array(sys.stdin.read().split(), dtype=np.int64)
n, m, R = I[:3]
r = I[3:3+R] - 1
a, b, c = I[3+R:].reshape(-1, 3).T
a -= 1; b -= 1
graph = csr_matrix((c, (a, b)), shape=(n, n))

def main():
    dist = floyd_warshall(graph, directed=False).astype(np.int64)
    *perms, = permutations(r)
    perms = np.array(perms)
    res = dist[perms[:, :-1], perms[:, 1:]]
    ans = np.amin(np.sum(res, axis=1))
    return ans

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

Solution (Python):
def main():
    from sys import stdin
    input = stdin.readline
    n, m, r = map(int, input().split())
    root = list(map(int, input().split()))
    abc = [list(map(int, input().split())) for _ in [0]*m]

    import numpy as np
    import scipy.sparse.csgraph as sp
    inf = float('inf')
    d = np.full((n, n), inf)
    for i in range(n):
        d[i][i] = 0
    for a, b, c in abc:
        d[a-1][b-1] = c
        d[b-1][a-1] = c
    
    s = sp.shortest_path(d)

    from itertools import permutations

    p = list(permutations(root))

    D = 10**10
    for i in p:
        d = 0
        for j in range(len(i)-1):
            d += s[i[j]-1][i[j+1]-1]
        D = min(D, d)
    print(int(D))


main()

Solution (Python):
def main():
  import numpy as np
  import itertools
  from scipy.sparse import csr_matrix
  from scipy.sparse.csgraph import floyd_warshall
  import sys
  readline = sys.stdin.readline
  readlines = sys.stdin.readlines

  N, M, R= map(int, readline().split())
  r = list(map(int,input().split()))
  lines = readlines()
  edge = np.array([line.split() for line in lines], dtype = np.int64).T
  graph = csr_matrix((edge[2], (edge[:2] - 1)), (N, N))
  distance_mat = floyd_warshall(graph,directed = False)
  
  ans = float("inf")
  for town in itertools.permutations(r,R):
    
    tmp = 0
    for i in range(R-1):
      tmp += distance_mat[town[i]-1][town[i+1]-1]
    ans = min(ans,tmp)
  print(int(ans))
main()

Solution (Python):
def main():
  import numpy as np
  import itertools
  from scipy.sparse import csr_matrix
  from scipy.sparse.csgraph import dijkstra
  import sys
  readline = sys.stdin.readline
  readlines = sys.stdin.readlines

  N, M, R= map(int, readline().split())
  r = list(map(int,input().split()))
  lines = readlines()
  edge = np.array([line.split() for line in lines], dtype = np.int64).T
  
  
  graph = csr_matrix((edge[2], (edge[:2] - 1)), (N, N))
  ans = float("inf")
  distance_mat = {}
  for i in r:
    distance_mat[i-1] = (dijkstra(graph, directed = False, indices = i-1))

  for town in itertools.permutations(r,R):
    
    tmp = 0
    for i in range(R-1):
      tmp += distance_mat[town[i]-1][town[i+1]-1]
    ans = min(ans,tmp)
  print(int(ans))
main()

Solution (Python):
import itertools

nmr = list(map(int,input().split()))
N,M,R = nmr[0],nmr[1],nmr[2]
perm = list(map(int,input().split()))
perm.sort()
dist = [[int(1e9) for i in range(N+1)] for j in range(N+1)]
res = int(1e11)


for i in range(M):
    abc = list(map(int,input().split()))
    a,b,c = abc[0],abc[1],abc[2]
    dist[a][b] = c
    dist[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(dist[i][j] > dist[i][k] + dist[k][j]):
                dist[i][j] = dist[i][k] + dist[k][j]


for dir in itertools.permutations(perm):
    direction = list(dir)
    tmpdir = 0
    for i in range(len(direction) - 1):
        tmpdir += dist[direction[i]][direction[i+1]]
    res = min(tmpdir,res)

print(res)

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

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

s = [[10**9]*N for i in range(N)]
t = list(map(int, input().split()))
for i in range(M):
    a, b, c = map(int, input().split())
    s[a-1][b-1] = c
    s[b-1][a-1] = c
    
s = floyd_warshall(s)
ans = float('inf')
for i in permutations(t):
    A_n = 0
    for j in range(R-1):
        A_n += s[i[j] - 1][i[j+1] - 1]
    ans = min(ans, A_n)
    
print(int(ans))

Solution (Python):


import itertools
import sys


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

W = [[10**10 for _ in range(N+1)] for _ in range(N+1)]
for i in range(M):
  a, b, c = map(int, input().split())
  W[a][b], W[b][a] = c, c

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


answer = 10**10
for v in itertools.permutations(r, R):
  tmp = 0
  for i in range(1, R):
    tmp += W[v[i]][v[i-1]]
  answer = min(answer, tmp)
print(answer)

Solution (Python):
import itertools
import sys
input = sys.stdin.buffer.readline

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

W = [[10**10 for _ in range(N+1)] for _ in range(N+1)]
for i in range(M):
  a, b, c = map(int, input().split())
  W[a][b], W[b][a] = c, c

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


answer = 10**10
for v in itertools.permutations(r, R):
  tmp = 0
  for i in range(1, R):
    tmp += W[v[i]][v[i-1]]
  answer = min(answer, tmp)
print(answer)

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

adj = [[] for i in range(N)]
for i in range(M):
    A, B, C = map(int, input().split())
    adj[-A].append((B, C))
    adj[-B].append((A, C))

import heapq

def Dijkstra(N, v_st, v_go):
    cost = [float('inf') for i in range(N)]

    pq = []
    heapq.heappush(pq, (0, v_st))

    while pq:
        c, v_now = heapq.heappop(pq)

        if v_now == v_go:
            return c

        if cost[-v_now] < c:
            continue

        cost[-v_now] = c

        for v, c2 in adj[-v_now]:
            if cost[-v_now] + c2 < cost[-v]:
                cost[-v] = cost[-v_now] + c2
                heapq.heappush(pq, (cost[-v], v))

cost_min = [[float('inf') for i in range(R)] for j in range(R)]

for i in range(R):
    for j in range(i, R):
        cost_min[i][j] = Dijkstra(N, r[i], r[j])
        cost_min[j][i] = cost_min[i][j]

import itertools
p = list(itertools.permutations(range(R)))

ans = float('inf')
for pp in p:
    c = 0
    for i in range(R - 1):
        c += cost_min[pp[i]][pp[i + 1]]

    ans = min(ans, c)
    
print(ans)

Solution (Python):
from itertools import permutations
def warshal_floyd(weights,N):
    d=weights
    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])
    return d

if __name__ == '__main__':
    N,M,R=list(map(int,input().split()))
    cities=[r-1 for r in list(map(int,input().split()))]
    weights=[[1e10 for i in range(N)] for j in range(N)]
    for i in range(M):
        a,b,c=list(map(int,input().split()))
        a-=1
        b-=1
        weights[a][b]=c
        weights[b][a]=c

    d=warshal_floyd(weights,N)
    mini_count=1e12
    for c in permutations(cities):
        count=sum(d[i][j] for i,j in zip(c,c[1:]))
        mini_count=min(mini_count,count)
    print(mini_count)

Solution (Python):
import itertools


def dijkstra(v, G):
    import heapq

    ret = [10 ** 10] * len(G)
    ret[v] = 0
    q = [(ret[i], i) for i in range(len(G))]
    heapq.heapify(q)

    while len(q):
        tmpr, u = heapq.heappop(q)
        if tmpr == ret[u]:
            for w, l in G[u]:
                if ret[w] > ret[u] + l:
                    ret[w] = ret[u] + l
                    heapq.heappush(q, (ret[w], w))
    return ret


N, M, R = map(int, input().split())
r = list(map(int, input().split()))
NE = [[] for _ in range(N)]
for _ in range(M):
    A, B, C = map(int, input().split())
    NE[A - 1].append((B - 1, C))
    NE[B - 1].append((A - 1, C))

RE = [[0] * R for _ in range(R)]
for iR in range(R):
    for jR in range(iR + 1, R):
        lR = dijkstra(r[iR] - 1, NE)[r[jR] - 1]
        RE[iR][jR] = lR
        RE[jR][iR] = lR

ans = 10 ** 10
for p in itertools.permutations(range(R)):
    ans = min(ans, sum([RE[p[i]][p[i + 1]] for i in range(R - 1)]))

print(ans)

Solution (Python):

import sys
import itertools

def solve(N: int, M: int, R: int, r: "List[int]", A: "List[int]", B: "List[int]", C: "List[int]"):
    from scipy.sparse import csr_matrix
    from scipy.sparse.csgraph import floyd_warshall
    matrix = [[0]*N for _ in range(N)]
    for i in range(M):
        matrix[A[i]-1][B[i]-1] = C[i]
        matrix[B[i]-1][A[i]-1] = C[i]
    
    dist_matrix = floyd_warshall(csgraph=matrix, directed=False)

    perm = list(itertools.permutations(r)) 

    answer = float('inf')
    for p in perm:
        a = 0
        for index in range(len(p)-1):
            a += dist_matrix[p[index]-1][p[index+1]-1]
        answer = min(answer,a)
    print(int(answer))
    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)) for _ in range(R)]  
    A = [int()] * (M)  
    B = [int()] * (M)  
    C = [int()] * (M)  
    for i in range(M):
        A[i] = int(next(tokens))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, M, R, r, A, B, C)

if __name__ == '__main__':
    main()

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

d = [[float("inf") for i in range(n)] for j 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



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

    return d 

d = warshall_floyd(d, n)
import itertools
ans = float("inf")
for balls in itertools.permutations(rl):
    a = 0
    for i in range(r-1):
        a += d[balls[i]-1][balls[i+1]-1]
    ans = min(ans, a)

print(ans)

Solution (Python):
from itertools import permutations

def warshall_floyd(d):
    
    n=len(d[0])
    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]
    return d

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


route_list=[[10**8]*N for _ in range(N)]

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

wa_list=warshall_floyd(route_list)
ans=30**9

for perm in permutations(r):
    
    cur = sum(wa_list[v][u] for v, u in zip(perm, perm[1:]))
    ans = min(ans, cur)

print(ans)

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

n, m, R = [int(i) for i in sys.stdin.readline().split()]
r_ls = [int(i) - 1 for i in sys.stdin.readline().split()]
INF = 10**18
graph = [[0 for i in range(n)] for j in range(n)]
for i in range(m):
    a, b, c = [int(i) for i in sys.stdin.readline().split()]
    a -= 1
    b -= 1
    graph[a][b] = c
    graph[b][a] = c

graph_new = csgraph_from_dense(graph)
res = floyd_warshall(graph_new)
res = res[r_ls][:,r_ls]

from itertools import permutations
best = INF
for p in permutations(range(R)):
    score = 0
    for i in range(R-1):
        score += res[p[i]][p[i+1]]
    best = min(best, score)
print(int(best))

Solution (Python):
import sys
from scipy.sparse.csgraph import floyd_warshall
from itertools import permutations
read = sys.stdin.read
readline = sys.stdin.readline

N, M, R = map(int, readline().split())
r = list(map(int, readline().split()))
ABC = map(int, read().split())

INF = float('inf')
graph = [[INF] * (N + 1) for _ in range(N + 1)]

for i in range(N + 1):
    graph[i][i] = 0

for A, B, C in zip(*[iter(ABC)] * 3):
    graph[A][B] = C
    graph[B][A] = C

distance = floyd_warshall(graph)
answer = 10 ** 9
for tour in permutations(r):
    tmp = 0
    for i, j in zip(tour, tour[1:]):
        tmp += distance[i][j]

    if tmp < answer:
        answer = tmp

print(int(answer))

Solution (Python):
import sys
from scipy.sparse.csgraph import floyd_warshall
from itertools import permutations
read = sys.stdin.read
readline = sys.stdin.readline

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

INF = float('inf')
graph = [[INF] * (N + 1) for _ in range(N + 1)]
ABC = map(int, read().split())

for i in range(N + 1):
    graph[i][i] = 0

for A, B, C in zip(*[iter(ABC)] * 3):
    graph[A][B] = C
    graph[B][A] = C

distance = floyd_warshall(graph, directed=False)
answer = 10 ** 9
for tour in permutations(r):
    tmp = 0
    for i, j in zip(tour, tour[1:]):
        tmp += distance[i][j]

    if tmp < answer:
        answer = tmp

print(int(answer))

Solution (Python):
import sys
from scipy.sparse.csgraph import floyd_warshall
from itertools import permutations
read = sys.stdin.read
readline = sys.stdin.readline

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

INF = float('inf')
graph = [[INF] * (N + 1) for _ in range(N + 1)]
ABC = map(int, read().split())

for i in range(N + 1):
    graph[i][i] = 0

for A, B, C in zip(*[iter(ABC)] * 3):
    graph[A][B] = C
    graph[B][A] = C

distance = floyd_warshall(graph, directed=False)
answer = 10 ** 9
for tour in permutations(r):
    tmp = 0
    for i in range(R - 1):
        tmp += distance[tour[i]][tour[i + 1]]

    if tmp < answer:
        answer = tmp

print(int(answer))

Solution (Python):

from heapq import heappop, heappush
from itertools import permutations

inf = 1 << 30

def dijkstra(source: int, edges: "List[Tuple[int, int]]") -> "List[int]":
    """
    Compute the distance of the shortest path from V_source to each vertex.

    Args:
        source: V_source
        edges: Edges info
    Returns:
        dist: A list of distance from V_source
    """
    edges_count = len(edges)
    dist = [inf] * edges_count
    dist[source] = 0
    undetermined = edges_count - 1  
    queue = [(0, source)]
    while queue:
        cost, v = heappop(queue)
        if cost > dist[v]:
            continue
        for next_cost, u in edges[v]:
            if cost + next_cost < dist[u]:
                dist[u] = cost + next_cost
                heappush(queue, (dist[u], u))
        undetermined -= 1
        if not undetermined:
            break
    return dist  

def main():
    N, M, R, *RABC = map(int, open(0).read().split())
    visit, ABC = RABC[:R], RABC[R:]
    edges = [[] for _ in range(N + 1)]
    for v, u, cost in zip(*[iter(ABC)] * 3):
        edges[v].append((cost, u)), edges[u].append((cost, v))
    dist = {v: dijkstra(v, edges) for v in visit}
    ans = inf
    for perm in permutations(visit):
        cur = sum(dist[v][u] for v, u in zip(perm, perm[1:]))
        ans = min(ans, cur)
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):

from heapq import heappop, heappush
from itertools import permutations

inf = 1 << 30

def dijkstra(source: int, edges: "List[Tuple[int, int]]") -> "List[int]":
    """
    Compute the distance of the shortest path from V_source to each vertex.

    Args:
        source: V_source
        edges: Edges info
    Returns:
        dist: A list of distance from V_source
    """
    edges_count = len(edges)
    dist = [inf] * edges_count
    dist[source] = 0
    undetermined = edges_count - 1  
    queue = [(0, source)]
    while queue:
        cost, v = heappop(queue)
        if cost > dist[v]:
            continue
        for next_cost, u in edges[v]:
            if cost + next_cost < dist[u]:
                dist[u] = cost + next_cost
                heappush(queue, (dist[u], u))
        undetermined -= 1
        if not undetermined:
            break
    return dist  

def main():
    N, M, R, *RABC = map(int, open(0).read().split())
    visit, ABC = RABC[:R], RABC[R:]
    edges = [[] for _ in range(N + 1)]
    for v, u, cost in zip(*[iter(ABC)] * 3):
        edges[v].append((cost, u)), edges[u].append((cost, v))
    dist = {v: dijkstra(v, edges) for v in visit}
    ans = inf
    for perm in permutations(visit):
        cur = sum(dist[v][u] for v, u in zip(perm, perm[1:]))
        ans = min(ans, cur)
    print(ans)


if __name__ == "__main__":
    main()