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

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

possible = permutations(r,R)
dist = [[float("inf") for k in range(N)]for i in range(N)]

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

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

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

Ans = float("inf")
for pos in possible:
    ans = 0
    for i in range(R-1):
        ans += dist[pos[i]-1][pos[i+1]-1]

    Ans = min(Ans,ans)

print(Ans)

Submission status: Accepted

Solution code:
from functools import reduce
import math
import itertools

def main():
    # 文字列の2進数を数値にする
    # '101' → '5'
    # 文字列の頭に'0b'をつけてint()にわたす
    # binary = int('0b'+'101',0)

    # 2進数で立っているbitを数える
    # 101(0x5) → 2
    # cnt_bit = bin(5).count('1')
    
    # N! を求める
    # f = math.factorial(N)

    # N の逆元
    # N_inv = pow(N,MOD-2,MOD)

    # nCr
    # Nの階乗 * rの階乗の逆元 * n-rの階乗の逆元
    
    # 切り捨て
    # 4 // 3
    # 切り上げ
    #-(-4 // 3)
    
    # 初期値用:十分大きい数(100億)
    INF = float("inf")

    # 大きな素数
    MOD = 10**9+7
    
    # 1文字のみを読み込み
    # 入力:2
    # a = input().rstrip()
    # 変数:a='2'
    
    # スペース区切りで標準入力を配列として読み込み
    # 入力:2 4 5 7
    # a, b, c, d = (int(_) for _ in input().split())  
    # 変数:a=2 b=4 c=5 d =7
    
    # 1文字ずつ標準入力を配列として読み込み
    # 入力:2 4 5 7
    # a = list(int(_) for _ in input().split())
    # 変数:a = [2, 4, 5, 7]    

    # 1文字ずつ標準入力を配列として読み込み
    # 入力:2457
    # a = list(int(_) for _ in input())
    # 変数:a = [2, 4, 5, 7]    
    N,M,R = (int(_) for _ in input().split())
    r = list(int(_)-1 for _ in input().split())
    a = []
    b = []
    c = []
    for i in range(M):
        s1,s2,s3 = (int(_) for _ in input().split())
        a.append(s1-1)
        b.append(s2-1)
        c.append(s3)
    d = []
    for i in range(N):
        d.append(list(INF for _ in range(N)))
        
    for i in range(N):
        for j in range(N):
            if i == j:
                d[i][j] = 0
    for i in range(M):
        if d[a[i]][b[i]] > c[i]:
            d[a[i]][b[i]] = c[i]
            d[b[i]][a[i]] = c[i]
    for k in range(N):
        for i in range(N):
            for j in range(N):
                if d[i][j] > d[i][k] + d[k][j]:
                    d[i][j] = d[i][k] + d[k][j]
    ans = INF
    for nodes in list(itertools.permutations(r)):
        cost = 0
        for i in range(len(nodes)-1):
            cost += d[nodes[i]][nodes[i+1]]
        ans = min(ans,cost)
    print(ans)
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
import heapq
import copy
import itertools

inf = float('inf')

def path(u, v):
    return frozenset((u, v))


class Graph_dijkstra(object):
    def __init__(self, V: "List[int]", E: "Set[FrozenSet[int, int]]", L: "Dict[FrozenSet[int, int], int]"):
        self.V = V
        self.E = E
        self.L = L
        self.adjacent = self.init_adjacent() # type: Dict[int: List[int]]
        self.shortest_path = self.init_shortest_path() # type: Dict[FrozenSet[int, int], int]
    
    def init_adjacent(self):
        ret = {v: [] for v in self.V}
        for e in self.E:
            el = list(e)
            ret[el[0]].append(el[1])
            ret[el[1]].append(el[0])
        return ret
    
    def init_shortest_path(self):
        ret = {path(s, g): inf for s, g in itertools.permutations(self.V, 2)}
        for v in self.V:
            ret[path(v, v)] = 0
        return ret
    
    def dijkstra(self, s: int):
        D = {v: inf for v in self.V}
        D[s] = 0
        prev = {v: None for v in self.V}
        Q = [(0, s)]

        while len(Q) > 0:
            du, u = heapq.heappop(Q)
            for v in self.adjacent[u]:
                e = path(u, v)
                alt = du + self.L[e]
                if alt < D[v]:
                    D[v] = alt
                    prev[v] = u
                    heapq.heappush(Q, (D[v], v))

        for v in self.V:
            self.shortest_path[path(s, v)] = D[v]

    def find_shortest_path(self, pair: "FrozenSet[int, int]"):
        d = self.shortest_path[pair]
        if d < inf:
            return d
        s = list(pair)[0]
        self.dijkstra(s)
        return self.shortest_path[pair]

def solve(N: int, M: int, R: int, r: "List[int]", A: "List[int]", B: "List[int]", C: "List[int]"):
    V = list(range(N))
    E = set()
    L = dict()
    
    for i in range(M):
        e = path(A[i], B[i])
        E.add(e)
        L[e] = C[i]

    G = Graph_dijkstra(V, E, L)
    for ri in r:
        G.dijkstra(ri)
    shortest = inf
    for p in itertools.permutations(r):
        path_len = 0
        for i in range(len(p)-1):
            path_len += G.find_shortest_path(path(p[i], p[i+1]))
        if path_len < shortest:
            shortest = path_len
    
    print(shortest)
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    R = int(next(tokens))  # type: int
    r = [ int(next(tokens))-1 for _ in range(R) ]  # type: "List[int]"
    A = [int()] * (M)  # type: "List[int]" 
    B = [int()] * (M)  # type: "List[int]" 
    C = [int()] * (M)  # type: "List[int]" 
    for i in range(M):
        A[i] = int(next(tokens))-1
        B[i] = int(next(tokens))-1
        C[i] = int(next(tokens))
    solve(N, M, R, r, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#D問題

#warshall_floyd法
def warshall_floyd(dist):
    #dist[i][j]: iからjへの最短距離
    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])
    return dist

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

dist = [[float("inf") for i in range(N)] for i in range(N)] 
#dist[u][v] : 辺uvのコスト(存在しないときはinf)
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 i in range(N):
    dist[i][i] = 0 #自身のところに行くコストは０
dist=warshall_floyd(dist)

ever=[]
MIN=100000000
def ans_func(ever):
    global R
    global r
    global dist
    global MIN
    
    if len(ever) == R:
        if R == 2:
            kari=dist[ever[0]][ever[1]]
            MIN=min(MIN,kari)
        else:
            kari=0
            for i in range(R-1):
                kari+=dist[ever[i]][ever[i+1]]
            MIN=min(MIN,kari)
    else:
        i=0
        for i in range(R):
            if r[i]-1 in ever:
                pass
            else:
                ever.append(r[i]-1)
                ans_func(ever)
                ever.remove(r[i]-1)
    return
ans_func(ever)
print(MIN)

Submission status: Accepted

Solution code:
n, m, r = map(int,input().split())
r_list = list(map(lambda x:int(x)-1,input().split()))
INF = float('inf')
edge = []
for _ in range(m):
    a,b,c = map(int,input().split())
    edge.append([a-1,b-1,c])
def warshall_floyd(n,edge):
    graph = [[INF]*n for _ in range(n)]
    for i in range(n):
        graph[i][i] = 0
    for a, b, c in edge:
        graph[a][b] = c
        graph[b][a] = c
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if graph[i][k] + graph[k][j] < graph[i][j] :
                    graph[i][j] = graph[i][k] + graph[k][j]
    return graph
g = warshall_floyd(n,edge)
from itertools import permutations
ans = INF
for arr in permutations(range(r)):
    tmp = 0
    for a,b in zip(arr,arr[1:]):
        t1,t2 = r_list[a],r_list[b]
        tmp += g[t1][t2]
    ans = min(ans,tmp)
print(ans)

Submission status: Accepted

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

#計算量O(V^3) V:頂点数
# 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 i == j:
                    dist[i][j] = 0
                elif 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 = [int(e)-1 for e in input().split()]

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

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

warshall_floyd(dist,N)

ans = inf

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

print(ans)

Submission status: Accepted

Solution code:
import heapq
from itertools import permutations
n, m, r = [int(item) for item in input().split()]
rs = [int(item) for item in input().split()]
abc = [[int(item) for item in input().split()] for _ in range(m)]
INF = 10**9

class Dijkstra:
    def __init__(self, adj):
        self.adj = adj
        self.num = len(adj)
        self.dist = [INF] * self.num
        self.prev = [INF] * self.num
        self.q = []

    def reset(self):
        self.dist = [INF] * self.num
        self.prev = [INF] * self.num
        self.q = []

    def calc(self, start, goal=None):
        self.dist[start] = 0
        heapq.heappush(self.q, (0, start))
        while len(self.q) != 0:
            prov_cost, src = heapq.heappop(self.q)
            if self.dist[src] < prov_cost:
                continue
            for dest in range(self.num):
                cost = self.adj[src][dest]
                if cost != INF and self.dist[dest] > self.dist[src] + cost:
                    self.dist[dest] = self.dist[src] + cost
                    heapq.heappush(self.q, (self.dist[dest], dest))
                    self.prev[dest] = src
        if goal is not None:
            return self.get_path(goal)
        else:
            return self.dist

    def get_path(self, goal):
        path = [goal]
        dest = goal

        while self.prev[dest] != INF:
            path.append(self.prev[dest])
            dest = self.prev[dest]
        return list(reversed(path))

path = [[INF] * n for _ in range(n)]
short_path = [[INF] * n for _ in range(n)]
for i in range(n):
    path[i][i] = 0
for a, b, c in abc:
    path[a-1][b-1] = path[b-1][a-1] = c

dij = Dijkstra(path)
for item in rs:
    for i in range(n):
        short_path[item-1][i] = dij.calc(item-1)[i]
    dij.reset()

ans = INF
for pattern in permutations(rs):
    distance = 0
    for i in range(1,r):
        distance += short_path[pattern[i-1]-1][pattern[i]-1]
    ans = min(ans, distance)
print(ans)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())


from functools import reduce
from itertools import permutations

from heapq import heappush, heappop

def dijkstra(graph:list, node:int, start:int) -> list:
    # 未探索のノードは距離INF
    INF = float("inf")
    dist = [INF]*node
    
    # 始点ノードの距離を0とし、dfsのためのpriority queを作成
    dist[start] = 0
    heap = [(0,start)]
    
    # 未探索のノードをpriority queueに入れる
    while heap:
        cost, cur_node = heappop(heap)
        
        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
                heappush(heap, (dist[nex_node], nex_node))
    
    return dist

def find_dist(fr: int, to: int):
    return graph[fr][to]

n,m,rn = li()
r = list(li_())
adj_list = [[] for _ in range(n)]
for _ in range(m):
    a,b,c = li()
    a -= 1
    b -= 1
    adj_list[a].append((c, b))
    adj_list[b].append((c, a))
    
graph = [[0]*rn for _ in range(rn)]
for i, ri in enumerate(r):
    dist = dijkstra(adj_list, n, ri)
    for j, rj in enumerate(r):
        graph[i][j] = dist[rj]

ans = float('inf')
for route in permutations(range(len(r)), len(r)):
    cand = 0
    for i,j in zip(route[:-1], route[1:]):
        cand += graph[i][j]
    
    ans = min(ans, cand)

print(ans)

Submission status: Accepted

Solution code:
from itertools import permutations 
inf=10**9
n, m, r1 = map(int, input().split())
r=list(map(int, input().split()))
abc=[list(map(int, input().split())) for _ in range(m)]
d=[[inf]*n for i in range(n)]
for ai, bi, ci in abc:
    d[ai-1][bi-1]=ci
    d[bi-1][ai-1]=ci
for k in range(n):
    for i in range(n-1):
        for j in range(i, n):
            dk=d[i][k]+d[k][j]
            if d[i][j]>dk:
                d[j][i]=dk
                d[i][j]=dk
permutations(r)
ans=inf
p=list(permutations(r))
for pi in p:
    res=0
    for i in range(r1-1):
        res+=d[pi[i]-1][pi[i+1]-1]
    if ans>res:
        ans=res
print(ans)

Submission status: Accepted

Solution code:
from itertools import permutations 
inf=10**9
n, m, r1 = map(int, input().split())
r=list(map(int, input().split()))
abc=[list(map(int, input().split())) for _ in range(m)]
d=[[inf]*n for i in range(n)]
for ai, bi, ci in abc:
    d[ai-1][bi-1]=ci
    d[bi-1][ai-1]=ci
for k in range(n):
    for i in range(n-1):
        for j in range(i, n):
            dk=d[i][k]+d[k][j]
            if d[i][j]>dk:
                d[j][i]=dk
                d[i][j]=dk
permutations(r)
ans=inf
for pi in permutations(r):
    res=0
    for i in range(r1-1):
        res+=d[pi[i]-1][pi[i+1]-1]
    if ans>res:
        ans=res
print(ans)

Submission status: Accepted

Solution code:
from itertools import permutations
N, M, R = map(int, input().split())
r = list(map(int, input().split()))
E = [list(map(int, input().split())) for _ in range(M)]
INF = 10 ** 9
d = [[INF for j in range(N)] for i in range(N)]
for i, j, c in E:
    d[i - 1][j - 1] = c
    d[j - 1][i - 1] = c
for k in range(N):
    for i in range(N - 1):
        for j in range(i, N):
            dk = d[i][k] + d[k][j]
            if d[i][j] > dk:
                d[i][j] = dk
                d[j][i] = dk
ans = 10 ** 9
for ri in permutations(r):
    x = 0
    for i in range(R - 1):
        x += d[ri[i] - 1][ri[i + 1] - 1]
    if ans > x:
        ans = x
print(ans)

Submission status: Accepted

Solution code:
def getN():
    return int(input())

def getlist():
    return list(map(int, input().split()))

import heapq
inf = 1000000000
ans = inf

def dijkstra(n, graph, start):
    # call n times
    h = []
    routes = [[inf, i] for i in range(n)]
    routes[start][0] = 0
    heapq.heappush(h, routes[start][1])
    while(h):
        cur = heapq.heappop(h)
        for edge in graph[cur]:
            target, cost = edge
            if routes[target][0] > routes[cur][0] + cost:
                routes[target][0] = routes[cur][0] + cost
                heapq.heappush(h, routes[target][1])

    return [route[0] for route in routes]


def dfs(depth, rlist, tmpcost, tmppos, dist):
    if depth == r-1:
        #print("return: cost = {}, terminal = {}".format(tmpcost, tmppos))
        return tmpcost
    else:
        ans = 100000000
        for rnum in rlist:
            if flag[rnum] == 0:
                flag[rnum] = 1
                #print("depth {} pos {} tmpcost {} ".format(depth, tmppos, tmpcost))
                returncost = dfs(depth+1, rlist, tmpcost+dist[rnum-1][tmppos-1], rnum, dist)
                flag[rnum] = 0
                if ans > returncost:
                    ans = returncost
        return ans

def floyd_nanotka(n):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if(dist[i][k] + dist[k][j] <  dist[i][j]):
                    dist[i][j] = dist[i][k] + dist[k][j]


n, m, r = getlist()
graph = [[] for i in range(n)]
rlist = getlist()
dist = [[inf for i in range(n)] for j in range(n)]
for i in range(n):
    dist[i][i] = 0

for i in range(m):
    v1, v2, cost = getlist()
    dist[v1-1][v2-1] = cost
    dist[v2-1][v1-1] = cost

#for i in range(n):
#    dist.append(dijkstra(n, graph, i))
floyd_nanotka(n)
#print(dist)
flag = [0 for i in range(n+1)]
ans_candidate = []
for i in rlist:
    flag[i] = 1
    ans_candidate.append(dfs(0, rlist, 0, i, dist))
    flag[i] = 0

print(min(ans_candidate))

Submission status: Accepted

Solution code:
from itertools import permutations as pe
from scipy.sparse.csgraph import floyd_warshall as wf
n,m,r=map(int,input().split())
s=[[(0 if i==j else float("inf"))for j in range(n+1)]for i in range(n+1)]
g=list(pe(list(map(int,input().split()))))
for i in range(m):
    a,b,c=map(int,input().split())
    s[a][b]=c
    s[b][a]=c
s=wf(s,directed=False)
k=float("inf")
for i in range(len(g)):
    d=g[i]
    c=0
    for j in range(1,len(d)):
        c+=s[d[j-1]][d[j]]
        if c>=k:
            break
    else:
        k=min(c,k)
print(int(k))

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall as wf
import itertools

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

G = [[float('inf')] * N for _ in range(N)]
for i in range(N):
    G[i][i] = 0
for _ in range(M):
    i, j, k = map(int, input().split())
    G[i - 1][j - 1] = k
    G[j - 1][i - 1] = k
    
wf = wf(G)

ans = float('inf')
for perm in itertools.permutations(r):
    tmp = 0
    for i in range(len(perm) - 1):
        tmp += wf[perm[i] - 1][perm[i + 1] - 1]
    ans = min(ans, tmp)
    
print(int(ans))

Submission status: Accepted

Solution code:
from itertools import permutations

def warshall_floyd(V, E):
    INF = 10 ** 9
    d = [[INF for j in range(V)] for i in range(V)]
    for i, j, c in E:
        d[i - 1][j - 1] = c
        d[j - 1][i - 1] = c
    for k in range(V):
        for i in range(V - 1):
            for j in range(i, V):
                dk = d[i][k] + d[k][j]
                if d[i][j] > dk:
                    d[i][j] = dk
                    d[j][i] = dk
    return d

N, M, R = map(int, input().split())
r = list(map(int, input().split()))
E = [list(map(int, input().split())) for _ in range(M)]
d = warshall_floyd(N, E)

ans = 10 ** 9
for ri in permutations(r):
    x = 0
    for i in range(R - 1):
        x += d[ri[i] - 1][ri[i + 1] - 1]
    if ans > x:
        ans = x
print(ans)

Submission status: Accepted

Solution code:
import sys
import numpy as np
from scipy.sparse.csgraph import floyd_warshall
from itertools import permutations

def main():
    input = sys.stdin.readline
    N, M, R = map(int, input().split())
    r = list(map(int, input().split()))

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

    G = floyd_warshall(np.array(A))

    ans = INF
    for root in permutations(r):
        cur = 0
        for i in range(R-1):
            s, g = root[i] -1, root[i+1] - 1
            cur += G[s][g]

        ans = min(ans, cur)

    return int(ans)


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

Submission status: Accepted

Solution code:
import sys
import numpy as np
from scipy.sparse.csgraph import floyd_warshall
from itertools import permutations


def main():
    input = sys.stdin.readline
    N, M, R = map(int, input().split())
    r = list(map(int, input().split()))

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

    D = np.array(A, dtype=int)
    G = floyd_warshall(D)

    """
    ans = INF
    for start in r[:2]:
        passed = [start]
        temp_ans = 0
        while len(passed) < len(r):
            cur = INF
            next_start = -1
            for dest in r:
                if dest in passed:
                    continue

                if A[start-1][dest-1] < cur:
                    next_start = dest
                    cur = A[start-1][dest-1]

            passed.append(next_start)
            start = next_start
            temp_ans += cur

        ans = min(ans, temp_ans)
    """

    ans = INF
    for root in permutations(r):
        cur = 0
        for i in range(R-1):
            s, g = root[i] -1, root[i+1] - 1
            cur += G[s][g]

        ans = min(ans, cur)

    return int(ans)


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

Submission status: Accepted

Solution code:
N,M,R=map(int,input().split())
X=list(map(int,input().split()))
from collections import defaultdict
from collections import deque
branch=defaultdict(set)
for m in range(M):
    a,b,c=map(int,input().split())
    branch[a]|={(b,c)}
    branch[b]|={(a,c)}
def makedist(x):
    dist=[float('inf')]*(N+1)
    dist[x]=0
    check={x,}
    while len(check)>0:
        now=check.pop()
        for b in branch[now]:
            if dist[now]+b[1]<dist[b[0]]:
                dist[b[0]]=dist[now]+b[1]
                check|={b[0],}
    return dist
data=dict()
for x in X:
    data[x]=makedist(x)
def roop(now,D,notvisit,ans):
    if len(notvisit)==0:
        return min(D,ans)
    for nex in notvisit:
        ans=roop(nex,D+data[now][nex],notvisit-{nex,},ans)
    return ans
ans=float('inf')
for x in X:
    ans=min(ans,roop(x,0,set(X),float('inf')))
print(ans)

Submission status: Accepted

Solution code:
import itertools
import math
from collections import deque
from collections import defaultdict
from itertools import permutations
import heapq
INF = float("inf")

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

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

def dijkstra(v):
    d = [INF] * N
    d[v] = 0
    hq =[(0,v)]

    while hq:
        u = heapq.heappop(hq)[1]
        for (v,c) in adj_cost[u]:
            if d[v] > d[u] + c:
                d[v] = d[u] +c
                heapq.heappush(hq,(d[u]+c,v))
    return d

ans = INF
table = {}
for i in r:
    table[i-1] = dijkstra(i-1)

for each in permutations(r):
    dis = 0
    for i in range(R-1):
        dis += table[each[i]-1][each[i+1]-1]

    ans = min(ans,dis)
print(ans)

Submission status: Accepted

Solution code:
import heapq


def construct_graph(A, B, C):
    M = len(A)
    graph = {}
    for i in range(M):
        a = A[i]
        b = B[i]
        c = C[i]
        if a not in graph:
            graph[a] = {}
        if b not in graph:
            graph[b] = {}
        graph[a][b] = c
        graph[b][a] = c
    return graph


def dijkstra(graph, s, t):
    q = [(0, s)]
    fix = set()
    d = {}
    d[s] = 0
    while len(q) > 0:
        cur_d, n = heapq.heappop(q)
        if n in fix:
            continue
        fix.add(n)
        if n == t:
            break
        for v in graph[n]:
            if v in fix:
                continue
            c = graph[n][v]
            if v not in d or d[v] > d[n] + c:
                d[v] = d[n] + c
            heapq.heappush(q, (d[v], v))
    return d[t]


def dijkstra_all(graph, nodes):
    d = {}
    for n in nodes:
        d[n] = {}
        for n2 in nodes:
            if n == n2: 
                continue
            if n2 not in d:
                d[n2] = {}
            d[n][n2] = dijkstra(graph, n, n2)
            d[n2][n] = d[n][n2]
    return d


def tsp_dist(graph):
    graph[-1] = {}
    for n in graph:
        if n == -1: continue
        graph[-1][n] = 0
    return tsp(graph, set(), -1)


def tsp(graph, visited, s):
    if len(visited) + 1 == len(graph):
        return 0
    min_d = None
    for n in graph[s]:
        if n in visited: continue
        c = graph[s][n]
        dist = tsp(graph, visited | set([s]), n) + c
        if min_d is None or min_d > dist:
            min_d = dist
    return min_d


def solve(r, A, B, C):
    graph = construct_graph(A, B, C)
    d = dijkstra_all(graph, r)
    minimum_dist = tsp_dist(d)
    return minimum_dist


def main():
    N, M, R = list(map(int, input().split(' ')))
    r = list(map(int, input().split(' ')))
    A = []
    B = []
    C = []
    for i in range(M):
        a, b, c = list(map(int, input().split(' ')))
        A.append(a)
        B.append(b)
        C.append(c)
    print(solve(r, A, B, C))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import dijkstra

n, m, r = map(int,input().split())
rs = list(map(int, input().split()))
edge = [[0]*n for i in range(n)]
for i in range(m):
    a, b, c = list(map(int, input().split()))
    a, b = a-1, b-1
    edge[a][b] = c
    edge[b][a] = c
dist = dijkstra(edge, directed=False, indices=[i for i in range(n)])

from itertools import permutations
ans = float("inf")
    
for v in permutations(rs, len(rs)):
    dist_tmp = 0
    for i in range(r-1):
        dist_tmp += dist[v[i]-1][v[i+1]-1]
    ans = min(ans, int(dist_tmp))
print(ans)

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall

n, m, r = map(int,input().split())
rs = list(map(int, input().split()))
edge = [[0]*n for i in range(n)]
for i in range(m):
    a, b, c = list(map(int, input().split()))
    a, b = a-1, b-1
    edge[a][b] = c
    edge[b][a] = c
dist = floyd_warshall(edge, directed=False)

from itertools import permutations
ans = float("inf")
    
for v in permutations(rs, len(rs)):
    dist_tmp = 0
    for i in range(r-1):
        dist_tmp += dist[v[i]-1][v[i+1]-1]
    ans = min(ans, int(dist_tmp))
print(ans)

Submission status: Accepted

Solution code:
inf = 10**15
import itertools
n,m,r = map(int,input().split())
city = list(map(int,input().split()))


dist = [[inf for i in range(n)] for i in range(n)]

#まず距離を初期化(入力に従う)
for i in range(m):
    ak,bk,ck = map(int,input().split())
    dist[ak-1][bk-1]  =ck
    dist[bk-1][ak-1]  =ck

for a in range(n):
    for b in range(n):
        for c in range(n):
            dist[b][c] = min(dist[b][c],dist[b][a]+dist[a][c])

#print(dist)

ans = inf
for v in itertools.permutations(city):
    cost = 0
    for i in range(len(v)-1):
        cost += dist[v[i]-1][v[i+1]-1]
    #print(v,cost)
    ans = min(ans,cost)

print(ans)

Submission status: Accepted

Solution code:
from scipy.sparse.csgraph import floyd_warshall
import itertools
n,m,r = map(int,input().split())
L = list(map(int,input().split()))
d = [[float("inf")]*n for i in range(n)]
for i in range(n):
    d[i][i] = 0
for i in range(m):
    a,b,l = map(int,input().split())
    d[a-1][b-1] = l
    d[b-1][a-1] = l
d = floyd_warshall(d)
ans = float('inf')
seq = []
for i in range(r):
  seq.append(i)
K = list(itertools.permutations(seq))
for i in range(len(K)):
  cur = 0
  for j in range(1,r):
    p = L[K[i][j-1]]-1
    q = L[K[i][j]]-1
    cur += d[p][q]
  if cur != float('inf'):
    if cur <= ans:
      ans = cur
print(int(ans))

Submission status: Accepted

Solution code:
def solve():
        from itertools import permutations
        N, M, R = map(int, input().split())
        rs = map(lambda x: int(x) - 1, input().split())
        dist, ans = [[float("inf") for _ in range(N)] for _ in range(N)], float("inf")
        for _ in range(M):
            v1, v2, d = map(int, input().split())
            dist[v1-1][v2-1] = dist[v2-1][v1-1] = d
        for i in range(N):
            dist[i][i] = 0
        for k in range(N):
            for i in range(N):
                for j in range(N):
                    if dist[i][j] > dist[i][k] + dist[k][j]:
                        dist[i][j] = dist[i][k] + dist[k][j]
        for r in permutations(rs):
            t = 0
            for i in range(R - 1):
                t += dist[r[i]][r[i + 1]]
            ans = min(t, ans)
        print(ans)

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
if __name__ == "__main__":
    from itertools import permutations
    N, M, R = map(int, input().split())
    rs = map(lambda x: int(x) - 1, input().split())
    dist = [[10**9 for _ in range(N)] for _ in range(N)]
    for _ in range(M):
        v1, v2, d = map(int, input().split())
        dist[v1-1][v2-1] = dist[v2-1][v1-1] = d
    for i in range(N):
        dist[i][i] = 0
    for k in range(N):
        for i in range(N):
            for j in range(N):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
    ans = 10**9
    for r in permutations(rs):
        t = 0
        for i in range(R-1):
            t += dist[r[i]][r[i+1]]
            if t > 10**9:
                break
        ans = min(t, ans)
    print(ans)

Submission status: Accepted

Solution code:
import itertools

INF = float("inf")


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


if __name__ == "__main__":
    main()