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 sys import stdin
import collections
import math
import itertools

n,m,r   = [int(x) for x in stdin.readline().rstrip().split()]
r_arr = [int(x) for x in stdin.readline().rstrip().split()]

ways = [[int(c)  for c in stdin.readline().rstrip().split()] for _ in range(m)]
inf = float('inf')
cost = [[inf] * n for _ in range(n)]
for i in range(n):
    cost[i][i] = 0

for way in ways:
    cost[way[0]-1][way[1]-1] = way[2]
    cost[way[1]-1][way[0]-1] = way[2]



for k in range(n):
    for i in range(n):
        for j in range(n):
            cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j])


tours = []
for perm in itertools.permutations(r_arr):
    d = 0
    for i in range(r-1):
        d += cost[perm[i]-1][perm[i+1]-1]
    tours.append(d)
print(min(tours))

Solution (Python):
import itertools

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

inf = float('inf')
dists = [[inf] * n for _ in range(n)]
for i in range(n):
    dists[i][i] = 0

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


for k in range(n):
    for i in range(n):
        for j in range(n):
            dists[i][j] = min(dists[i][j], dists[i][k] + dists[k][j])

tours = []
for perm in itertools.permutations(rs):
    d = 0
    for i in range(r-1):
        d += dists[perm[i]][perm[i+1]]
    tours.append(d)
print(min(tours))

Solution (Python):
from itertools import permutations

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

d = [[10000000000]*N for _ in range(N)]
for i in range(N):
  d[i][i] = 0

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 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])
      
perms = permutations(r, R)
ans = 10000000000
for perm in perms:
  now = 0
  for i in range(R-1):
    now += d[perm[i]][perm[i+1]]
  ans = min(ans, now)
  
print(ans)

Solution (Python):
from itertools import combinations, permutations

N, M, R = [int(_) for _ in input().split()]
r_list = [int(_) for _ in input().split()]

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

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

ans = INF * R
for p in permutations(range(R)):
    val = 0
    for i in range(R - 1):
        c = r_list[p[i]]-1
        n = r_list[p[i + 1]]-1
        val += G[c][n]
    ans = min(ans, val)
print(ans)

Solution (Python):
from itertools import permutations
n,m,R = map(int,input().split())
r = [int(i)-1 for i in input().split()]
INF = float("INF")
d = [[INF]*n for _ in range(n)]
for _ in range(m):
    a,b,c = map(int,input().split())
    a -= 1
    b -= 1
    d[a][b] = c
    d[b][a] = 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 p in permutations(r):
    res = 0
    for i in range(R-1):
        res += d[p[i]][p[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()))
p = list(itertools.permutations(r))
dp = [[float('inf')]*N for _ in range(N)]
for i in range(M):
    a,b,c = map(int,input().split())
    dp[a-1][b-1] = c
    dp[b-1][a-1] = c
for i in range(N):
    dp[i][i] = 0

for k in range(N):
    for i in range(N):
        for j in range(N):
            dp[i][j] = min(dp[i][j], dp[i][k]+dp[k][j])
ans = float('inf')
for v in p:
    temp = 0
    for i in range(len(v)-1):
        temp += dp[v[i]-1][v[i+1]-1]
    ans = min(ans,temp)

print(ans)

Solution (Python):
from itertools import permutations
n, m, r = map(int, input().split())
INF = 1 << 60

d = [[INF] * n for i in range(n)]
rs = list(map(int, input().split()))

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

def warshall_floyd(d):
    """
    input
        d : 初期全点対距離
    output
        d : 最適化後全点対距離
    """
    n = len(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

d_optimized = warshall_floyd(d)


ans = INF
for inds in permutations([r-1 for r in rs]):
    cnt = 0
    for i in range(r-1):
        prev = inds[i]
        nxt = inds[i+1]
        cnt += d_optimized[prev][nxt]
    ans = min(ans,cnt)
print(ans)

Solution (Python):
from itertools import permutations
import sys
input = sys.stdin.readline
N, M, R = map(int, input().split())
r = [int(i)-1 for i in input().split()]
D = [[float("inf")] * N for _ in range(N)]
for a, b, c in [[int(i) for i in input().split()] for _ in range(M)]:
    a -= 1
    b -= 1
    D[a][b] = c
    D[b][a] = 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])

ans = float("inf")
for l in permutations(range(R)):
    l = list(l)
    c = 0
    for i in range(R - 1):
        c += D[r[l[i]]][r[l[i + 1]]]
    ans = min(ans, c)
print(ans)

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

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

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

dist = floyd_warshall(graph).astype(int)
orders = list(itertools.permutations(r, R))

ans = float('inf')
for order in orders:
  d = 0
  for u, v in zip(order, order[1:]):
    d += dist[u][v]
  ans = min(ans, d)

print(ans)

Solution (Python):
from heapq import heapify, heappush, heappop

inf = float("inf")
def dijkstra(start):  
    vsize = len(graph)
    dist = [inf] * vsize
    seen = [False] * vsize
    prev = [None] * vsize
    pq = []
    heapify(pq)

    dist[start] = 0
    heappush(pq, (0, start))  
    while pq:
        cost, u = heappop(pq)
        seen[u] = True
        if dist[u] < cost:
            continue
        for v, w in graph[u]:
            temp_cost = dist[u] + w
            if not seen[v] and temp_cost < dist[v]:
                dist[v] = temp_cost
                prev[v] = u
                heappush(pq, (dist[v], v))
    return dist, prev
N, M, R = map(int, input().split())
rlist = list(map(int, input().split()))
graph = [[] for _ in range(N)]
for _ in range(M):
    A, B, C = map(int, input().split())
    graph[A-1].append((B-1, C))
    graph[B-1].append((A-1, C))
shortest_path = [dijkstra(i) for i in range(N)]
from itertools import permutations
ans = 10**9

for path in permutations(rlist):
    cost = 0
    for i in range(R-1):
        cost += shortest_path[path[i]-1][0][path[i+1]-1]
    ans = min(ans, cost)
print(ans)

Solution (Python):
from heapq import heapify, heappush, heappop

inf = float("inf")
def dijkstra(graph, start):  
    vsize = len(graph)
    dist = [inf] * vsize
    seen = [False] * vsize
    prev = [None] * vsize
    pq = []
    heapify(pq)

    dist[start] = 0
    heappush(pq, (0, start))  
    while pq:
        cost, u = heappop(pq)
        seen[u] = True
        if dist[u] < cost:
            continue
        for v, w in graph[u]:
            temp_cost = dist[u] + w
            if not seen[v] and temp_cost < dist[v]:
                dist[v] = temp_cost
                prev[v] = u
                heappush(pq, (dist[v], v))
    return dist, prev
N, M, R = map(int, input().split())
rlist = list(map(int, input().split()))
graph = [[] for _ in range(N)]
for _ in range(M):
    A, B, C = map(int, input().split())
    graph[A-1].append((B-1, C))
    graph[B-1].append((A-1, C))
shortest_path = [dijkstra(graph, i) for i in range(N)]
from itertools import permutations
ans = 10**9

for path in permutations(rlist):
    cost = 0
    for i in range(R-1):
        cost += shortest_path[path[i]-1][0][path[i+1]-1]
    ans = min(ans, cost)
print(ans)

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

def main():

    
    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 

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

    d = [[10**10] * 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

    d = warshall_floyd(d, n)
    ans = 10**10

    ptr = list(itertools.permutations(R, len(R))) 
    for i in ptr:
        tmp = 0
        for j in range(len(i)-1):
            tmp += d[i[j]][i[j+1]]
        ans = min(ans, tmp)

    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
import heapq
import itertools
import sys

input = sys.stdin.readline

def main():

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

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

    def dijkstra(edges, s):
        hq = []
        d = [-1] * n
        d[s] = 0
        heapq.heappush(hq, (0, s))
        while hq:
            d1, p = heapq.heappop(hq)
            for p2, d2 in edges[p]:
                if d[p2] == -1 or d[p2] > d1 + d2:
                    d[p2] = d1 + d2
                    heapq.heappush(hq, (d1+d2, p2))
        return d

    ans = 10**10
    d = []

    for i in range(n):
        d1 = dijkstra(roots, i)
        d.append(d1)

    ptr = list(itertools.permutations(R, len(R))) 

    for i in ptr:
        tmp = 0
        for j in range(len(i) - 1):
            tmp += d[i[j]][i[j+1]]
        ans = min(ans, tmp)

    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
from itertools import permutations
import heapq

def dijkstra(N, G, s):
    INF = 10**40
    d = [INF] * N
    d[s] = 0
    q = [(0, s)]
    while q:
        c, v = heapq.heappop(q)
        if d[v] < c:
            continue
        for t, co in G[v]:
            if d[v] + co < d[t]:
                d[t] = d[v] + co
                heapq.heappush(q, (d[t], t))
    return d


def main():
    N, M, _ = map(int, input().split())
    R = list(map(int, input().split()))
    R = [r - 1 for r in R]
    G = [[] for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        G[a - 1].append((b - 1, c))
        G[b - 1].append((a - 1, c))
    RM = []
    for r in R:
        d = dijkstra(N, G, r)
        RM.append([d[rr] for rr in R])
    m = 10 ** 40
    for i in permutations(range(len(R))):
        t = i[0]
        c = 0
        for r in i[1:]:
            c += RM[t][r]
            t = r
        m = min(m, c)
    return m


print(main())

Solution (Python):
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix
from itertools import permutations
def main():
    N, M, R = map(int, input().split())
    r = list(map(int, input().split()))
    r = [i-1 for i in r]
    l = [[0] * N for _ in range(N)]
    for _ in range(M):
        a, b, c = map(int, input().split())
        a -= 1
        b -= 1
        l[a][b] = c
        l[b][a] = c
    G = csr_matrix(l)
    dd = dijkstra(G, directed=False)
    ans = 10**100
    for i in permutations(r, len(r)):
        t = 0
        for j in range(len(r)-1):
            t += dd[i[j]][i[j+1]]
        ans = min(ans, t)
    return int(ans)
print(main())

Solution (Python):
import sys
from collections import Counter
from collections import deque
import heapq
import math
import fractions
import bisect
import itertools
def input(): return sys.stdin.readline().strip()
def mp(): return map(int,input().split())
def lmp(): return list(map(int,input().split()))



n,m,r=mp()
l=lmp()
d = [[float("inf")]*(n+1) for i in range(n+1)] 
for i in range(m):
    x,y,z = map(int,input().split())
    d[x][y] = z
    d[y][x] = z
for i in range(n+1):
    d[i][i] = 0
for k in range(n+1):
        for i in range(n+1):
            for j in range(n+1):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])

lis=list(itertools.permutations(l))
ans=float("inf")
for k in range(len(lis)):
    c=0
    for i in range(r-1):
        c+=d[lis[k][i]][lis[k][i+1]]
    ans=min(ans,c)
print(ans)

Solution (Python):







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


def main():
    N, M, R = map(int,input().split()) 
    d = [[float("inf")]*N for i in range(N)]
    
    r = list(map(int,input().split()))
    for i in range(M):
        u, v, w = map(int,input().split())
        d[u-1][v-1] = w
        d[v-1][u-1] = w
    for i in range(N):
        d[i][i] = 0 
    cost = floyd_warshall(d)
    L = list(permutations(r, R))
    ret = 10**9
    for rt in L:
        cos = 0
        for i in range(1,R):
            cos += cost[rt[i]-1][rt[i-1]-1]
        ret = min(ret, cos)
    print(int(ret))

if __name__ == '__main__':
    main()

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

dp = [[float("INF")]*(N+1) for _ in range(N+1)]
for _ in range(M):
    a,b,c = map(int,input().split())
    dp[a][b] = c
    dp[b][a] = c

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

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

from itertools import permutations
ans = float("INF")
for pattern in permutations(R):
    cost = 0
    for i in range(r-1):
        cost += dp[pattern[i]][pattern[i+1]]
    ans = min(ans,cost)
print(ans)

Solution (Python):


import sys






















from itertools import product, permutations  







def main():
    mod = 1000000007                
    inf = float('inf')              
    
    sys.setrecursionlimit(10**6)    
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    from copy import deepcopy
    def warshall_floyd(adj_mat_with_weight):
        '''
        Warshall-Floyd 法 (O(V^3), 1 sec だと v~500 とかが限界)
        全点対間の最短経路を三次元 DP で求める
        Args:
            adj_mat_with_weight (list): 重みを記録した隣接行列 (非接続頂点は inf)
        Returns:
            dp (list): dp[i][j] を見れば全頂点を使用可能な時の i j 最短距離がわかる。最後に dp[i][i] が負になっていたら負サイクルが存在するということ
        '''
        V = len(adj_mat_with_weight)
        
        dp = deepcopy(adj_mat_with_weight)
        for i in range(V):
            dp[i][i] = 0
        
        for k in range(1, V+1):
            for i in range(V):
                for j in range(V):
                    
                    dp[i][j] = min(dp[i][j], dp[i][k-1]+dp[k-1][j])
        return dp
    

    n, m, r = mi()
    R = lmi_0()
    adj_mat_with_weight = [[inf] * n for _ in range(n)]
    for _ in range(m):
        a, b, dist = mi_0()
        dist += 1
        adj_mat_with_weight[a][b] = dist
        adj_mat_with_weight[b][a] = dist
    
    dp = warshall_floyd(adj_mat_with_weight)
    
    ans = inf
    for pattern in permutations(R):
        total_dist = 0
        for i in range(1, r):
            total_dist += dp[pattern[i-1]][pattern[i]]
        ans = min(ans, total_dist)
    print(ans)


    




if __name__ == "__main__":
    main()

Solution (Python):
from itertools import groupby, accumulate, product, permutations, combinations
def solve():
    ans = float('inf')
    N, M, R = map(int, input().split())
    r = list(map(int, input().split()))
    d = [[float('inf')]*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])
    for p in permutations(r,R):
        cnt = 0
        for i in range(R-1):
            if d[p[i]-1][p[i+1]-1]<float('inf'):
                cnt += d[p[i]-1][p[i+1]-1]
            else:
                break
        else:
            ans = min(ans,cnt)
    return ans
print(solve())

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


def main():
    N, M, R = list(map(int, input().split(' ')))
    towns = list(map(lambda t: int(t) - 1, input().split(' ')))
    A = np.zeros((N, N), dtype=int)
    for _ in range(M):
        a, b, c = list(map(int, input().split(' ')))
        A[a-1][b-1] = c
        A[b-1][a-1] = c
    fw = floyd_warshall(A)
    d = fw[towns, :][:, towns]
    min_d = 10**12
    for trip in itertools.permutations(range(R)):
        min_d = min([min_d, sum([d[trip[i]][trip[i+1]] for i in range(len(trip) - 1)])])
    print(int(min_d))


if __name__ == '__main__':
    main()

Solution (Python):
from itertools import permutations

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

li = [[0 for i in range(N+1)]for j in range(N+1)]

for _ in range(M):
    a,b,c = map(int,input().split())
    li[a][b] = c
    li[b][a] = c

def all_pairs_shortest_paths(W):
    inf = 10**18
    
    n = len(W)
    
    res = [[0] * n for i in range(n)]
    
    for i in range(n):
        for j in range(i, n):
            if i == j:
                val = 0
            elif W[i][j]:
                val = W[i][j]
            else:
                val = inf
            res[i][j] = res[j][i] = val
    
    for k in range(n):
        for u in range(n):
            for v in range(n):
                res[u][v] = min(res[u][v], res[u][k] + res[k][v])
    return res

lin = all_pairs_shortest_paths(li)

pos = list(permutations(r))

mi = 10**18

for i in pos:
    l = 0
    for j in range(1,R):
        l += lin[i[j-1]][i[j]]
    mi = min(mi,l)

print(mi)

Solution (Python):
from itertools import permutations

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=map(int,input().split())
r=list(map(int,list(input().split())))
g=[[float("inf")]*n for _ in range(n)]
for i in range(m):
    a,b,c=map(int,input().split())
    g[a-1][b-1]=c
    g[b-1][a-1]=c
for i in range(n):
    g[i][i]=0
g=warshall_floyd(n,g)
ans=float("inf")
for p in list(permutations(r)):
    tmp=0
    for i in range(R-1):
        tmp+=g[p[i]-1][p[i+1]-1]
    ans=min(ans,tmp)
print(ans)

Solution (Python):
N,M,R= list(map(int,input().split()))
towns = list(map(int,input().split()))
for i in range(R):
    towns[i] += -1

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

dists = [[float("inf")]*N for i in range(R)]

import heapq

for i in range(R):
    town = towns[i]
    dist = dists[i]
    dist[town] = 0
    used = [0]*N
    used[town] = 1

    nextlist = []
    for next in G[town]:
        heapq.heappush(nextlist,next)

    while len(nextlist):
        minnext = heapq.heappop(nextlist)
        if used[minnext[1]]==1:
            continue
        v = minnext[1]
        dist[v] = minnext[0]
        used[v] = 1
        for next in G[v]:
            if used[next[1]]==0:
                heapq.heappush(nextlist,[next[0]+dist[v],next[1]])

from itertools import permutations
townorders = list(permutations(towns))

out = float("inf")
for townorder in townorders:
    cand = 0
    for i in range(R-1):
        now = townorder[i]
        nowind = towns.index(now)
        next = townorder[i+1]
        cand += dists[nowind][next]
    if cand<out:
        out=cand
print(out)

Solution (Python):
from itertools import permutations

n, m, r = map(int, input().split())
city = list(map(int, input().split()))
for i in range(r):
    city[i] -= 1
to = [[] for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    a -= 1; b -= 1
    to[a].append([b, c])
    to[b].append([a, c])

INF = 10**15
dist = [[INF for _ in range(n)] for _ in range(n)]
for i in range(n):
    dist[i][i] = 0
    for j in range(len(to[i])):
        dist[i][to[i][j][0]] = to[i][j][1]
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 = INF
for v in permutations(city):
    tmp = 0
    for i in range(r-1):
        tmp += dist[v[i]][v[i+1]]
    ans = min(ans, tmp)

print(ans)

Solution (Python):
import sys, re
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees
from collections import deque, defaultdict, Counter
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop, heapify
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, M, R = MAP()
r = LIST()
ABC = [LIST() for _ in range(M)]

dist_matrix = [[INF]*N for _ in range(N)]

for A, B, C in ABC:
	dist_matrix[A-1][B-1] = C
	dist_matrix[B-1][A-1] = C

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





from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall
 
graph = csr_matrix(dist_matrix) 
dist_matrix = floyd_warshall(graph, directed=False) 





ans = INF
for x in permutations(r):
	tmp = 0
	for i in range(1, R):
		tmp += dist_matrix[x[i-1]-1][x[i]-1]
	ans = min(ans, tmp)

print(int(ans))

Solution (Python):
import sys, re
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees
from collections import deque, defaultdict, Counter
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop, heapify
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, M, R = MAP()
r = LIST()
ABC = [LIST() for _ in range(M)]

dist_matrix = [[INF]*N for _ in range(N)]
for A, B, C in ABC:
	dist_matrix[A-1][B-1] = C
	dist_matrix[B-1][A-1] = C

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




def Warshall_Floyd(dist, N):
	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])

Warshall_Floyd(dist_matrix, N)




ans = INF
for x in permutations(r):
	dis = 0
	for i in range(1, R):
		dis += dist_matrix[x[i-1]-1][x[i]-1]
	ans = min(ans, dis)

print(ans)

Solution (Python):
import sys, re
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees
from collections import deque, defaultdict, Counter
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop, heapify
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, M, R = MAP()
r = LIST()
ABC = [LIST() for _ in range(M)]

dist_matrix = [[0]*N for _ in range(N)]
for A, B, C in ABC:
	dist_matrix[A-1][B-1] = C
	dist_matrix[B-1][A-1] = C





from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall
 
graph = csr_matrix(dist_matrix) 
dist_matrix = floyd_warshall(graph, directed=False) 





ans = INF
for x in permutations(r):
	dis = 0
	for i in range(1, R):
		dis += dist_matrix[x[i-1]-1][x[i]-1]
	ans = min(ans, dis)

print(int(ans))

Solution (Python):
import sys, re
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees
from collections import deque, defaultdict, Counter
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop, heapify
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N, M, R = MAP()
r = LIST()
dist_matrix = [[INF]*N for _ in range(N)]

for _ in range(M):
	A, B, C = MAP()
	dist_matrix[A-1][B-1] = C
	dist_matrix[B-1][A-1] = C

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





def Warshall_Floyd(dist, N):
	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])

Warshall_Floyd(dist_matrix, N)





ans = INF
for x in permutations(r):
	tmp = x[0]
	dis = 0
	for i in range(1, R):
		dis += dist_matrix[tmp-1][x[i]-1]
		tmp = x[i]
	ans = min(ans, dis)
	
print(int(ans))

Solution (Python):
import itertools

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

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

def dijkstra(start,cost):
    d=[float("inf")]*N
    used=[False]*N
    d[start]=0

    while True:
        v=-1
        for i in range(N):
            if (not used[i]) and (v==-1):
                v=i
            elif (not used[i]) and d[i]<d[v]:
                v=i
        if v==-1:
            break
        used[v]=True

        for j in range(N):
            d[j]=min(d[j],d[v]+cost[v][j])
    
    return d

d=[]
for i in range(N):
    d.append(dijkstra(i,graph))

ans=float("inf")
for city in itertools.permutations(r):
    tmp=0
    for i in range(n-1):
        tmp+=d[city[i]-1][city[i+1]-1]
    ans=min(ans,tmp)
print(ans)

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

import sys
INF=float('inf')

road=[[INF]*n for _ in range(n)]

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


for k in range(n):
    
    for s in range(n):
        
        for g in range(n):
            road[s][g]=min(road[s][g],road[s][k]+road[k][g])

import itertools
rlist=list(itertools.permutations(r))

result=10**9
for item in rlist:
    tmp=0
    from_town=item[0]
    for to_town in item[1:]:
        tmp+=road[from_town-1][to_town-1]
        from_town=to_town
    result=min(result,tmp)

print(result)

Solution (Python):
import numpy as np
import scipy.sparse as sps
import scipy.misc as spm
import collections as col
import functools as func
import itertools as ite
import fractions as frac
import math as ma
import copy as cp
import sys
def sinput(): return sys.stdin.readline()
def iinput(): return int(sinput())
def imap(): return map(int, sinput().split())
def fmap(): return map(float, sinput().split())
def iarr(): return list(imap())
def farr(): return list(fmap())
def sarr(): return sinput().split()
def gcd(numbers): return func.reduce(frac.gcd, numbers)
def lcm(numbers): return func.reduce(LCM, numbers)
sys.setrecursionlimit(10**7)
mod = 10 ** 9 + 7
inf = np.inf

n,m,r = imap()
cities = map(lambda x: int(x)-1, sinput().split())
abc = np.array([iarr() for i in range(m)])
a,b,c = abc.T[0]-1, abc.T[1]-1, abc.T[2]
graph = sps.csr_matrix((c,(a,b)),(n,n))
wf = sps.csgraph.floyd_warshall(graph,directed=0).astype(int)

anss = []
for city in ite.permutations(cities):
    ans = 0
    for i in range(r-1): ans += wf[city[i]][city[i+1]]
    anss.append(ans)
print(min(anss))

Solution (Python):
import numpy as np
import scipy.sparse as sps
import scipy.misc as spm
import collections as col
import functools as func
import itertools as ite
import fractions as frac
import math as ma
import copy as cp
import sys
def sinput(): return sys.stdin.readline()
def iinput(): return int(sinput())
def imap(): return map(int, sinput().split())
def fmap(): return map(float, sinput().split())
def iarr(): return list(imap())
def farr(): return list(fmap())
def sarr(): return sinput().split()
def gcd(numbers): return func.reduce(frac.gcd, numbers)
def lcm(numbers): return func.reduce(LCM, numbers)
sys.setrecursionlimit(10**7)
mod = 10 ** 9 + 7
inf = np.inf

n,m,r = imap()
cities = map(lambda x: int(x)-1, sinput().split())
abc = np.array([iarr() for i in range(m)])
a,b,c = abc.T[0]-1, abc.T[1]-1, abc.T[2]
graph = sps.csr_matrix((c,(a,b)),(n,n))
wf = sps.csgraph.floyd_warshall(graph,directed=0).astype(np.int64)

anss = []
for city in ite.permutations(cities):
    ans = 0
    for i in range(r-1): ans += wf[city[i]][city[i+1]]
    anss.append(ans)
print(min(anss))