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



Sample input:
3 3 3
1 2 3
1 2 1
2 3 1
3 1 4


Sample output:
2

Submission status: Accepted

Solution code:
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 = warshall(N, ABCs)
#     ans = INF
#     for way in permutations(Rs):
#         tans = 0
#         for s, e in zip(way, way[1:]):
#             tans += dists[s - 1][e - 1]
#         ans = min(ans, tans)
#     return ans


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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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()

Submission status: Accepted

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

Submission status: Accepted

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

# dist[i][j]: iからjへのコスト,  n:頂点数
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)

Submission status: Accepted

Solution code:
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])

#print("距離行列は以下")
#for i in range(n+1):
    #print(dist[i])

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)

Submission status: Accepted

Solution code:
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 # min(c1, 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)

Submission status: Accepted

Solution code:
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
  
#tree = [[] for i in range(n)]

#for i in range(m):
#  a,b,c = map(int,input().split())
#  tree[a-1].append([b-1,c])
#  tree[b-1].append([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)

Submission status: Accepted

Solution code:
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 i in range(start):
    #     V[i] = W[i][start]
    #     for e in E[i]:
    #         if e > start:
    #             hq.heappush(q, (V[i] + D[(i,e)], e))
    for e in E[start]:
        if V[e] == -1:
            hq.heappush(q, (D[start, e],e))
    # print(V, q)
    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(N):
#     W[i] = dijkstra(E,d,i,W)
    # print(W)
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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
n, m, r = list(map(int, input().split()))
rs = list(map(int, input().split()))
# construct map
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)

Submission status: Accepted

Solution code:
n, m, r = list(map(int, input().split()))
rs = list(map(int, input().split()))
# construct map
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)

Submission status: Accepted

Solution code:
n, m, r = list(map(int, input().split()))
rs = list(map(int, input().split()))
# construct map
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)

Submission status: Accepted

Solution code:
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)]))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)
    # 非接続要素が「float("inf")」なら省略可
    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)

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
# coding:utf-8

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)

Submission status: Accepted

Solution code:
# coding:utf-8

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)

Submission status: Accepted

Solution code:
from itertools import permutations
N, M, Rn = map(int, input().split())
R = list(map(lambda x: int(x) - 1, input().split()))

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

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

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

print(ans)

Submission status: Accepted

Solution code:
import heapq
import itertools

def dijkstra(graph, node, start):
    dist = [float("inf") for _ in range(node)]

    dist[start] = 0
    q = []
    heapq.heappush(q, (0, start))

    while q:
        cost, cur_node = heapq.heappop(q)

        if dist[cur_node] < cost:
            continue

        for nex_cost, nex_node in graph[cur_node]:
            dist_cand = dist[cur_node] + nex_cost
            if dist_cand < dist[nex_node]:
                dist[nex_node] = dist_cand
                heapq.heappush(q, (dist[nex_node], nex_node))

    return dist

n, m, R = map(int, input().split())
r = list(map(int, input().split()))
adj = [[] for _ in range(n)]
for i in range(m):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    adj[a].append((c, b))
    adj[b].append((c, a))
shortest = []
for i in range(n):
    shortest.append(dijkstra(adj, n, i))
ans = float("INF")
for i in itertools.permutations(r):
    s = 0
    for j in range(R - 1):
        s += shortest[i[j] - 1][i[j + 1] - 1]
    ans = min(ans, s)
print(ans)

Submission status: Accepted

Solution code:
import itertools
import heapq

V, E, R = [int(_) for _ in input().split()]
r = [int(_) - 1 for _ in input().split()]  # 0-indexed
G = {}
for i in range(V):
    G[i] = {}
    G[i][i] = 0

for _ in range(E):
    s, t, c = [int(_) for _ in input().split()]
    s -= 1  # 0-indexed
    t -= 1  # 0-indexed
    G[s][t] = c
    G[t][s] = c

INF = float('inf')

Ds = []
for r_index in range(R):
    que = []
    d = 0
    i = r[r_index]
    D = [INF] * V
    D[i] = 0
    used = [False] * V
    used[i] = True

    while True:
        for j in G[i].keys():
            heapq.heappush(que, (d + G[i][j], j))
        v = -1
        while que:
            d, j = heapq.heappop(que)
            if not used[j]:
                v = j
                break
        if v == -1:
            break
        else:
            used[v] = True
            D[v] = d
            i = v
    Ds += [D]
ans = INF
for array in itertools.permutations(range(R), R):
    d = 0
    for i in range(R - 1):
        d += Ds[array[i]][r[array[i + 1]]]
    ans = min(ans, d)
print(ans)

Submission status: Accepted

Solution code:
from itertools import permutations
import sys
def main():
    N, M, R = map(int, input().split())
    rs = [x - 1 for x in map(int, input().split())]
    # グラフを作る
    dist = [[float('inf')] * (N) for _ in range(N)]
    for e in sys.stdin:
        A, B, C = map(int, e.split())
        dist[A - 1][B - 1] = dist[B - 1][A - 1] = C
    # ワーシャルフロイドで全頂点間距離算出
    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]
    # 組み合わせ全探索
    ans = float('inf')
    for p in permutations(rs):
        ans = min(ans, sum(dist[u][v] for u, v in zip(p, p[1:])))
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from itertools import permutations
import sys
import gc
def main():
    N, M, R = map(int, input().split())
    rs = [x - 1 for x in map(int, input().split())]
    # グラフを作る
    dist = [[float('inf')] * (N) for _ in range(N)]
    for e in sys.stdin:
        A, B, C = map(int, e.split())
        dist[A - 1][B - 1] = dist[B - 1][A - 1] = C
    # ワーシャルフロイドで全頂点間距離算出
    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]
    # 組み合わせ全探索
    ans = float('inf')
    for p in permutations(rs):
        tmp = 0
        for u, v in zip(p, p[1:]):
            tmp += dist[u][v]
            if tmp > ans:
                break
        else:
            ans = tmp
    print(ans)
if __name__ == '__main__':
    gc.disable()
    main()

Submission status: Accepted

Solution code:
from itertools import permutations
import sys
def main():
    N, M, R = map(int, input().split())
    rs = [x - 1 for x in map(int, input().split())]
    # グラフを作る
    dist = [[float('inf')] * (N) for _ in range(N)]
    for e in sys.stdin:
        A, B, C = map(int, e.split())
        dist[A - 1][B - 1] = dist[B - 1][A - 1] = C
    # ワーシャルフロイドで全頂点間距離算出
    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]
    # 組み合わせ全探索
    ans = float('inf')
    for p in permutations(rs):
        tmp = 0
        for u, v in zip(p, p[1:]):
            tmp += dist[u][v]
            if tmp > ans:
                break
        else:
            ans = tmp
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict
from heapq import heappop, heappush
import itertools
n, m, r = map(int, input().split())
rli = list(map(int, input().split()))
d = []
for i in range(m):#h:高さ
    d.append([int(m) for m in input().split()])


dist = d

class Graph(object):
    """
    隣接リストによる有向グラフ
    """

    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, src, dst, weight=1):
        self.graph[src].append((dst, weight))

    def get_nodes(self):
        return self.graph.keys()


class Dijkstra(object):
    """
    ダイクストラ法（二分ヒープ）による最短経路探索
    計算量: O((E+V)logV)
    """

    def __init__(self, graph, start):
        self.g = graph.graph

        # startノードからの最短距離
        # startノードは0, それ以外は無限大で初期化
        self.dist = defaultdict(lambda: float('inf'))
        self.dist[start] = 0

        # 最短経路での1つ前のノード
        self.prev = defaultdict(lambda: None)

        # startノードをキューに入れる
        self.Q = []
        heappush(self.Q, (self.dist[start], start))

        while self.Q:
            # 優先度（距離）が最小であるキューを取り出す
            dist_u, u = heappop(self.Q)
            if self.dist[u] < dist_u:
                continue
            for v, weight in self.g[u]:
                alt = dist_u + weight
                if self.dist[v] > alt:
                    self.dist[v] = alt
                    self.prev[v] = u
                    heappush(self.Q, (alt, v))

    def shortest_distance(self, goal):
        """
        startノードからgoalノードまでの最短距離
        """
        return self.dist[goal]

    def shortest_path(self, goal):
        """
        startノードからgoalノードまでの最短経路
        """
        path = []
        node = goal
        while node is not None:
            path.append(node)
            node = self.prev[node]
        return path[::-1]
# (src, dst, weight)
inputs = dist

g = Graph()
for src, dst, weight in inputs:
    g.add_edge(src, dst, weight)
    g.add_edge(dst, src, weight)
spdi = {}

for i in rli:
    for j in rli:
        d = Dijkstra(g, i)
        sp = format(d.shortest_distance(j))
        spdi[str(j) + "+" + str(i)] = int(sp)
realroot = float("INF")
for pa in itertools.permutations(rli, len(rli)):
    root = 0
    for i in range(1, len(pa)):
        root += spdi[str(pa[i]) + "+" + str(pa[i - 1])]
    if root < realroot:
        realroot = root

print(realroot)