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

# rの訪れ方を全パターン試して、最小の距離のものを答えにする。
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))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from heapq import heapify, heappush, heappop

inf = float("inf")
def dijkstra(start):  # graphは隣接リスト(繋がっている先, コスト)
    vsize = len(graph)
    dist = [inf] * vsize
    seen = [False] * vsize
    prev = [None] * vsize
    pq = []
    heapify(pq)

    dist[start] = 0
    heappush(pq, (0, start))  # heapではtuple[0]で比較されるのでこの順番で追加する
    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)

Submission status: Accepted

Solution code:
from heapq import heapify, heappush, heappop

inf = float("inf")
def dijkstra(graph, start):  # graphは隣接リスト(繋がっている先, コスト)
    vsize = len(graph)
    dist = [inf] * vsize
    seen = [False] * vsize
    prev = [None] * vsize
    pq = []
    heapify(pq)

    dist[start] = 0
    heappush(pq, (0, start))  # heapではtuple[0]で比較されるのでこの順番で追加する
    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)

Submission status: Accepted

Solution code:
import sys, itertools
input = sys.stdin.readline

def main():

    # d[i][j]は2頂点間i, j間の移動コストを格納, Vは頂点数
    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[i][j]に頂点i, j間の最短距離を格納

    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))) # 順列列挙 5P3
    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()

Submission status: Accepted

Solution code:
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))) # 順列列挙 5P3

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

# ワーシャルフロイド法
# 全頂点間最短路
# d[i][j]は2頂点間i, j間の移動コストを格納, Mは頂点数

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


def main():
    N, M, R = map(int,input().split()) #N:頂点数　M:辺の数
    d = [[float("inf")]*N for i in range(N)]
    #d[u][v] : 辺uvのコスト(存在しないときはinf)
    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()

Submission status: Accepted

Solution code:
N,M,r = map(int,input().split())
R = list(map(int,input().split()))
#dp[i][j][k] -> 町iまで経由地点として使える。j,kの最短移動距離
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)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    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):
                    # new 2d-table # old 2d-table
                    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()

Submission status: Accepted

Solution code:
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 #自身への最短経路は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())

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import sys, re
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2
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

#for i in range(N):
#	print(dist_matrix[i])

#ワーシャルフロイド法  注意 PyPy非対応!!!!
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall
 
graph = csr_matrix(dist_matrix) #隣接行列からcsr行列をつくる
dist_matrix = floyd_warshall(graph, directed=False) #無向の場合directed=False
#dist_matrixの中身はfloatになっているので注意！

#for i in range(N):
#	print(dist_matrix[i])

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

Submission status: Accepted

Solution code:
import sys, re
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2
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

#for i in range(N):
#	print(dist_matrix[i])

#ワーシャルフロイド法  注意 PyPy非対応!!!!
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import floyd_warshall
 
graph = csr_matrix(dist_matrix) #隣接行列からcsr行列をつくる
dist_matrix = floyd_warshall(graph, directed=False) #無向の場合directed=False
#dist_matrixの中身はfloatになっているので注意！

#for i in range(N):
#	print(dist_matrix[i])

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

Submission status: Accepted

Solution code:
import sys, re
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees#, log2
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

#for i in range(N):
#	print(dist_matrix[i])
#print()

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)

#for i in range(N):
#	print(dist_matrix[i])


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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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