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: Time Limit Exceeded

Solution code:
N,M,R = map(int,input().split())
r = list(map(int,input().split()))
r.sort()
G = [[10**9 for i in range(N+1)] for j in range(N+1)]
for i in range(M):
    a,b,c = map(int,input().split())
    G[a][b] = min(G[a][b],c)
    G[b][a] = G[a][b]
def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    for k in range(1,N+1):
        for i in range(1,N+1):
            for j in range(1,N+1):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d
warshall_floyd(G)
import itertools
ans = 10**9
for v in itertools.permutations(r):
    v = list(v)
    a = 0
    s = v.pop(0)
    for i in range(R-1):
        t = v[i]
        a += G[s][t]
        s = t
    ans = min(a,ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
N,M,R = list(map(int,input().split()))
r = list(map(int,input().split()))
r = [i-1 for i in r]
ABC = [[float('inf') for i in range(N)]for j in range(N)]
for i in range(N):
    ABC[i][i] = 0
for i in range(M):
    a,b,c = list(map(int,input().split()))
    a -= 1
    b -= 1
    ABC[a][b] = c
    ABC[b][a] = c
for k in range(N):
    for i in range(N):
        for j in range(N):
            ABC[i][j] = min(ABC[i][j],ABC[i][k]+ABC[k][j])
ans = float('inf')
for i in permutations(r):
    cost = 0
    now = i[0]
    for j in range(1,len(i)):
        cost += ABC[now][i[j]]
        now = i[j]
    ans = min(ans,cost)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import heapq

def dijkstra(n, tc_edges, s):
    
    min_dist = [float('inf')] * n
    min_dist[s] = 0
    next_v = []
    heapq.heappush(next_v, (0, s))
    path = [-1] * n
    
    while True:
        if len(next_v) == 0: break
        d, v = heapq.heappop(next_v)
        
        for u, d in tc_edges[v]:
            if min_dist[u] > min_dist[v] + d:
                min_dist[u] = min_dist[v] + d
                heapq.heappush(next_v, (min_dist[u], u))
                path[u] = v
                
    return min_dist, path
    
n, m, r = map(int, input().split())
r = list(map(int, input().split()))
edge = [[] for _ in range(n)]

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

dist = [dijkstra(n, edge, i)[0] for i in range(n)]

ans = float('inf')
for pr in permutations(r):
    temp = 0
    for i in range(len(r)-1):
        temp += dist[pr[i]-1][pr[i+1]-1]
        if temp >= ans: break
    
    ans = min(ans, temp)
    
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from itertools import *
import copy
from heapq import *


N,M,R=map(int,input().split())
Rlst=list(map(int,input().split()))
ABC=[list(map(int,input().split())) for i in range(M)]

data=[[] for i in range(N+1)]
nagasa={}
for a,b,c in ABC:
    data[a].append(b)
    data[b].append(a)
    A,B=min(a,b),max(a,b)
    nagasa.update({str(A)+" "+str(B):c})
mokutekiti=[[100000*200+1 for i in range(R)] for m in range(R)]
for r1i in range(R-1):
    for r2i in range(r1i+1,R):
        r1=Rlst[r1i]
        r2=Rlst[r2i]
        visited=set([r1])
        stack=[0]
        heapify(stack)
        dic={0:[r1]}
        while stack:
            m=heappop(stack)
            #if not m in visited:
            #visited.add(m)
            a=dic[m].pop()
            visited.add(a)
            for b in data[a]:
                if not b in visited or b==r2:
                    A,B=min(a,b),max(a,b)
                    tempm=m+nagasa[str(A)+" "+str(B)]
                    if b==r2:
                        if mokutekiti[r1i][r2i]>tempm:
                            mokutekiti[r1i][r2i]=tempm
                            mokutekiti[r2i][r1i]=tempm
                    else:
                        heappush(stack,tempm)
                        if tempm in dic:
                            dic[tempm].append(b)
                        else:
                            dic.update({tempm:[b]})



value=[]
for lst in permutations([i for i in range(R)],R):
    nagasa=0
    for i in range(R-1):
        nagasa+=mokutekiti[lst[i]][lst[i+1]]
    value.append(nagasa)
print(min(value))

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from itertools import *
import copy

N,M,R=map(int,input().split())
Rlst=list(map(int,input().split()))
ABC=[list(map(int,input().split())) for i in range(M)]

data=[[] for i in range(N+1)]
nagasa={}
for a,b,c in ABC:
    data[a].append(b)
    data[b].append(a)
    A,B=min(a,b),max(a,b)
    nagasa.update({str(A)+" "+str(B):c})
mokutekiti=[[0 for i in range(R)] for m in range(R)]
for r1i in range(R-1):
    for r2i in range(r1i+1,R):
        r1=Rlst[r1i]
        r2=Rlst[r2i]
        stack=deque([[r1,set([r1]),r1]])
        visited=set([r1])
        ikulst=set()
        while stack:
            a,miti,mae=stack.popleft()
            for b in data[a]:
                if b!=mae:
                    if not b in visited:
                        visited.add(b)
                        tempmiti=copy.copy(miti)
                        tempmiti.add(b)
                        if b==r2:
                            ikulst=ikulst|tempmiti
                        else:
                            stack.append([b,tempmiti,a])
                    elif b in ikulst:
                        ikulst=ikulst|miti



        stack=[[r1,0]]
        minpoint=[100000*200+1 for i in range(N+1)]
        while stack:
            a,m=stack.pop()
            for b in data[a]:
                if b in ikulst:
                    A,B=min(a,b),max(a,b)
                    tempm=m+nagasa[str(A)+" "+str(B)]
                    if tempm<minpoint[b]:
                        minpoint[b]=tempm
                        if b==r2:
                            pass
                        else:
                            stack.append([b,tempm])
        mokutekiti[r1i][r2i]=minpoint[r2]
        mokutekiti[r2i][r1i]=minpoint[r2]

value=[]
for lst in permutations([i for i in range(R)],R):
    nagasa=0
    for i in range(R-1):
        nagasa+=mokutekiti[lst[i]][lst[i+1]]
    value.append(nagasa)
print(min(value))

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from itertools import *
import copy

N,M,R=map(int,input().split())
Rlst=list(map(int,input().split()))
ABC=[list(map(int,input().split())) for i in range(M)]

data=[[] for i in range(N+1)]
nagasa={}
for a,b,c in ABC:
    data[a].append(b)
    data[b].append(a)
    A,B=min(a,b),max(a,b)
    nagasa.update({str(A)+" "+str(B):c})
mokutekiti=[[0 for i in range(R)] for m in range(R)]
for r1i in range(R-1):
    for r2i in range(r1i+1,R):
        r1=Rlst[r1i]
        r2=Rlst[r2i]
        stack=deque([[r1,set([r1])]])
        visited=set([r1])
        ikulst=set()
        while stack:
            a,miti=stack.popleft()
            for b in data[a]:
                if not b in visited:
                    visited.add(b)
                    tempmiti=copy.copy(miti)
                    tempmiti.add(b)
                    if b==r2:
                        ikulst=ikulst|tempmiti
                    else:
                        stack.append([b,tempmiti])
                elif b in ikulst:
                    for i in miti:
                        ikulst=ikulst|miti



        stack=[[r1,0]]
        minpoint=[100000*200+1 for i in range(N+1)]
        while stack:
            a,m=stack.pop()
            for b in data[a]:
                if b in ikulst:
                    A,B=min(a,b),max(a,b)
                    tempm=m+nagasa[str(A)+" "+str(B)]
                    if tempm<minpoint[b]:
                        minpoint[b]=tempm
                        if b==r2:
                            pass
                        else:
                            stack.append([b,tempm])
        mokutekiti[r1i][r2i]=minpoint[r2]
        mokutekiti[r2i][r1i]=minpoint[r2]

value=[]
for lst in permutations([i for i in range(R)],R):
    nagasa=0
    for i in range(R-1):
        nagasa+=mokutekiti[lst[i]][lst[i+1]]
    value.append(nagasa)
print(min(value))

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from itertools import *
import copy

N,M,R=map(int,input().split())
Rlst=list(map(int,input().split()))
ABC=[list(map(int,input().split())) for i in range(M)]

data=[[] for i in range(N+1)]
nagasa={}
for a,b,c in ABC:
    data[a].append(b)
    data[b].append(a)
    A,B=min(a,b),max(a,b)
    nagasa.update({str(A)+" "+str(B):c})
mokutekiti=[[0 for i in range(R)] for m in range(R)]
for r1i in range(R-1):
    for r2i in range(r1i+1,R):
        r1=Rlst[r1i]
        r2=Rlst[r2i]
        stack=deque([[r1,[r1]]])
        visited=set([r1])
        ikulst=set()
        while stack:
            a,miti=stack.popleft()
            for b in data[a]:
                if not b in visited:
                    visited.add(b)
                    tempmiti=copy.copy(miti)
                    tempmiti.append(b)
                    if b==r2:
                        for i in tempmiti:
                            ikulst.add(i)
                    else:
                        stack.append([b,tempmiti])
                elif b in ikulst:
                    for i in miti:
                        ikulst.add(i)



        stack=[[r1,0]]
        minpoint=[100000*200+1 for i in range(N+1)]
        while stack:
            a,m=stack.pop()
            for b in data[a]:
                if b in ikulst:
                    A,B=min(a,b),max(a,b)
                    tempm=m+nagasa[str(A)+" "+str(B)]
                    if tempm<minpoint[b]:
                        minpoint[b]=tempm
                        if b==r2:
                            pass
                        else:
                            stack.append([b,tempm])
        mokutekiti[r1i][r2i]=minpoint[r2]
        mokutekiti[r2i][r1i]=minpoint[r2]

value=[]
for lst in permutations([i for i in range(R)],R):
    nagasa=0
    for i in range(R-1):
        nagasa+=mokutekiti[lst[i]][lst[i+1]]
    value.append(nagasa)
print(min(value))

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from itertools import *
import copy

N,M,R=map(int,input().split())
Rlst=list(map(int,input().split()))
ABC=[list(map(int,input().split())) for i in range(M)]

data=[[] for i in range(N+1)]
nagasa={}
for a,b,c in ABC:
    data[a].append(b)
    data[b].append(a)
    A,B=min(a,b),max(a,b)
    nagasa.update({str(A)+" "+str(B):c})
mokutekiti=[[0 for i in range(R)] for m in range(R)]
for r1i in range(R-1):
    for r2i in range(r1i+1,R):
        r1=Rlst[r1i]
        r2=Rlst[r2i]
        stack=[[r1,0]]
        minpoint=[100000*200+1 for i in range(N+1)]
        while stack:
            a,m=stack.pop()
            for b in data[a]:
                A,B=min(a,b),max(a,b)
                tempm=m+nagasa[str(A)+" "+str(B)]
                if tempm<minpoint[b]:
                    minpoint[b]=tempm
                    if b==r2:
                        pass
                    else:
                        stack.append([b,tempm])
        mokutekiti[r1i][r2i]=minpoint[r2]
        mokutekiti[r2i][r1i]=minpoint[r2]

value=[]
for lst in permutations([i for i in range(R)],R):
    nagasa=0
    for i in range(R-1):
        nagasa+=mokutekiti[lst[i]][lst[i+1]]
    value.append(nagasa)
print(min(value))

Submission status: Time Limit Exceeded

Solution code:
from collections import *
from itertools import *
import copy

N,M,R=map(int,input().split())
Rlst=list(map(int,input().split()))
ABC=[list(map(int,input().split())) for i in range(M)]

data=[[] for i in range(N+1)]
nagasa={}
for a,b,c in ABC:
    data[a].append(b)
    data[b].append(a)
    A,B=min(a,b),max(a,b)
    nagasa.update({str(A)+" "+str(B):c})
mokutekiti=[[0 for i in range(R)] for m in range(R)]
for r1i in range(R-1):
    for r2i in range(r1i+1,R):
        r1=Rlst[r1i]
        r2=Rlst[r2i]
        nagasalst=[]

        stack=[[r1,set([r1]),0]]
        while stack:
            a,visited,m=stack.pop()
            for b in data[a]:
                if not b in visited:
                    tempvisited=copy.copy(visited)
                    tempvisited.add(b)
                    A,B=min(a,b),max(a,b)
                    tempm=m+nagasa[str(A)+" "+str(B)]
                    if b==r2:
                        nagasalst.append(tempm)
                    else:

                        stack.append([b,tempvisited,tempm])
        nagasalst=min(nagasalst)
        mokutekiti[r1i][r2i]=nagasalst
        mokutekiti[r2i][r1i]=nagasalst

value=[]
for lst in permutations([i for i in range(R)],R):
    nagasa=0
    for i in range(R-1):
        nagasa+=mokutekiti[lst[i]][lst[i+1]]
    value.append(nagasa)
print(min(value))

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
 
N, M, R = map(int, input().split())
r = [a-1 for a in [int(x) for x in input().split()]]
d = [[float("inf")]*N for _ in range(N)]

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

for a in range(N):
    d[a][a] = 0

res = float("inf")

for k in range(N):
    for i in range(N):
        for j in range(N):
            if d[i][k]+d[k][j] < d[i][j]:
                d[i][j] = d[i][k]+d[k][j]

for p in permutations(r):
    distance = 0
    for i in range(len(p)-1):
        distance += d[p[i]][p[i+1]]
    res = min(distance, res)

print(res)

Submission status: Time Limit Exceeded

Solution code:
import itertools
n, m, r = map(int, input().split())
t = list(map(int, input().split()))
for i in range(r):
    t[i] -= 1
d = [[10 * 18 for i in range(n)] for j in range(n)]
for i in range(n):
    d[i][i] = 0

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

perm = []
for i in range(r):
    perm.append(i)
ans = 10**18
for p in itertools.permutations(perm):
    now = 0
    for i in range(r-1):
        now += d[t[p[i]]][t[p[i + 1]]]
    ans = min(ans, now)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    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()) #n:頂点数　m:辺の数 r:訪れる町の数
R = list(map(int,input().split()))

d = [[float("inf") for i in range(n)] for i in range(n)] 
#d[u][v] : 辺uvのコスト(存在しないときはinf)
for i in range(m):
    x, y, z = map(int,input().split())
    d[x-1][y-1] = z
    d[y-1][x-1] = z
for i in range(n):
    d[i][i] = 0 #自身のところに行くコストは０
wa = warshall_floyd(d)

# 訪れる町の順番を順列で用意
from itertools import permutations
ptn = permutations(R)

ans = 10**19
for p in ptn:
  cost = 0
  roots = [(j-1, i-1) for i, j in zip(p, p[1:])]
  for i, j in roots:
    cost += wa[i][j]
  ans = min(ans, cost)
  
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import sys
input = sys.stdin.readline

if __name__ == "__main__":
    N, M, RR = map(int, input().split())
    R = list(map(int, input().split()))
    INF = float("inf")
    T = [[INF] * N for _ in range(N)]
    for _ in range(M):
        a, b, c = tuple(map(int, input().split()))
        T[a-1][b-1] = c
        T[b-1][a-1] = c
    for k in range(N):
        for i in range(N):
            for j in range(N):
                if T[i][j] > T[i][k]+T[k][j]:
                    T[i][j] = T[i][k]+T[k][j]
    print(min(sum(T[rs[i]-1][rs[i+1]-1] for i in range(RR-1)) for rs in permutations(R)))

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import sys
input = sys.stdin.readline

if __name__ == "__main__":
    N, M, _ = map(int, input().split())
    R = list(map(int, input().split()))
    INF = float("inf")
    T = [[INF] * N for _ in range(N)]
    for _ in range(M):
        a, b, c = tuple(map(int, input().split()))
        T[a-1][b-1] = c
        T[b-1][a-1] = c
    for k in range(N):
        for i in range(N):
            for j in range(N):
                T[i][j] = min(T[i][j],T[i][k]+T[k][j])

    print(min(sum(T[r1-1][r2-1] for r1, r2 in zip(rs, rs[1:])) for rs in permutations(R)))

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
N, M, _ = map(int, input().split())
R = list(map(int, input().split()))
T = [[0] * N for _ in range(N)]
for _ in range(M):
    a, b, c = tuple(map(int, input().split()))
    T[a-1][b-1] = c
    T[b-1][a-1] = c
for k in range(N):
    for i in range(N):
        for j in range(N):
            T[i][j] = min(T[i][j],T[i][k]+T[k][j])

print(min(sum(T[r1-1][r2-1] for r1, r2 in zip(rs, rs[1:])) for rs in permutations(R)))

Submission status: Time Limit Exceeded

Solution code:
import itertools
n,m,r=map(int,input().split())
rx=[int(i) for i in input().split()]
inf=100000000
wf=[[inf]*n for i in range(n)]
for i in range(n):
    wf[i][i]=0

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

for k in range(n):
    for i in range(n):
        for j in range(n):
            if wf[i][j]>wf[i][k]+wf[k][j]:
                wf[i][j]=wf[i][k]+wf[k][j]
cnt=0
l=list(itertools.permutations([i for i in range(r)]))
cnt=inf
for i in l:
    cnt_sub=0
    for j in range(r-1):
        cnt_sub+=wf[rx[i[j]]-1][rx[i[j+1]]-1]
    cnt=min(cnt,cnt_sub)
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import itertools
n,m,r=map(int,input().split())
rx=[int(i) for i in input().split()]
inf=100000000000
wf=[[inf]*n for i in range(n)]
for i in range(n):
    wf[i][i]=0

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

for k in range(n):
    for i in range(n):
        for j in range(n):
            if wf[i][j]>wf[i][k]+wf[k][j]:
                wf[i][j]=wf[i][k]+wf[k][j]
cnt=0
l=list(itertools.permutations([i for i in range(r)]))
cnt=inf
for i in l:
    cnt_sub=0
    for j in range(r-1):
        cnt_sub+=wf[rx[i[j]]-1][rx[i[j+1]]-1]
    cnt=min(cnt,cnt_sub)
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
import itertools
n,m,r=map(int,input().split())
rx=[int(i) for i in input().split()]
inf=100000000000
wf=[[inf]*n for i in range(n)]
for i in range(n):
    wf[i][i]=0

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

for k in range(n):
    for i in range(n):
        for j in range(n):
            wf[i][j]=min(wf[i][j],wf[i][k]+wf[k][j])
cnt=0
l=list(itertools.permutations([i for i in range(r)]))
#print(l)
cnt=inf
for i in l:
    cnt_sub=0
    for j in range(r-1):
        cnt_sub+=wf[rx[i[j]]-1][rx[i[j+1]]-1]
    cnt=min(cnt,cnt_sub)
print(cnt)

Submission status: Time Limit Exceeded

Solution code:
def warshall_floyd(d):
    #d[i][j]: iからjへの最短距離
    for k in range(1,n+1):
        for i in range(1,n+1):
            for j in range(1,n+1):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d
  
  
n,m,r = map(int,input().split()) 
lists=list(map(int,input().split()))
d = [[float("inf") for i in range(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 #自身のところに行くコストは０
dislist=warshall_floyd(d)

import itertools

U=list(itertools.permutations(lists))

mini=10**100
for some in U:
  dd=0
  for j in range(r-1):
    if dislist[some[j]][some[j+1]]!="inf":
      dd+=dislist[some[j]][some[j+1]]
    else:
      break
  mini=min(mini,dd)
print(mini)

Submission status: Time Limit Exceeded

Solution code:
#%%
import itertools

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

n, m, R = map(int, input().split())
r = list(map(lambda x: int(x)-1,input().split()))
dist = [[float("inf")] * n for _ 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, b = a-1, b-1
    dist[a][b] = c
    dist[b][a] = c
dist = warshall_floyd(dist)

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

Submission status: Time Limit Exceeded

Solution code:
# ABC073 D - joisino's travel
import itertools
N,M,R=map(int, input().split())
r=list(map(int, input().split()))
inf=float("inf")
mat=[[inf]*N for _ in range(N)]
dist=[inf]*N
visited=[False]*N
for i in range(M):
    a,b,c=map(int,input().split())
    if mat[a-1][b-1]>c:
        mat[a-1][b-1]=mat[b-1][a-1]=c

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

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

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

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
import itertools


def warshal_floyd(d):
    # d[i][j] := iからjへの最短距離
    global N
    for k in range(N):
        for i in range(N):
            for j in range(N):
                d[i][j] = min(d[i][j], d[i][k] + d[k][j])
    # "今現在求まっているiからjへの最短距離"と"今現在求まっているiからkへの最短距離 + 今現在求まっているkからjへの最短距離 の和"を比較する
    return d


N, M, R = map(int, input().split())  # N個の町, M本の道, R個の町を訪れることになった
town = list(map(lambda x: int(x)-1, input().split()))
distant = [[float('inf')]*N for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    distant[a][b] = c
    distant[b][a] = c
for i in range(N):
    distant[i][i] = 0


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

Submission status: Time Limit Exceeded

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


def warshal_floyd(d):
    # d[i][j] := iからjへの最短距離
    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])
    # "今現在求まっているiからjへの最短距離"と"今現在求まっているiからkへの最短距離 + 今現在求まっているkからjへの最短距離 の和"を比較する
    return d


N, M, R = map(int, input().split())  # N個の町, M本の道, R個の町を訪れることになった
town = list(map(lambda x: int(x)-1, input().split()))
distant = [[float('inf')]*N for _ in range(N)]
for _ in range(M):
    a, b, c = map(int, input().split())
    a -= 1
    b -= 1
    distant[a][b] = c
    distant[b][a] = c
for i in range(N):
    distant[i][i] = 0

warshal_floyd(distant)
# print(distant)  # Rは最大8だから全てを試しても大丈夫
ans = 10**9
for x in itertools.permutations(town):
    x = list(x)
    now = x[0]
    tmp = 0
    for i in range(1, len(x)):
        tmp += distant[now][x[i]]
        now = x[i]
    ans = min(ans, tmp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-

import sys

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

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

    res = deepcopy(graph)
    for i in range(N):
        # 始点 = 終点、は予め距離0にしておく
        res[i][i] = 0
    # 全頂点の最短距離
    for k in range(N):
        for i in range(N):
            for j in range(N):
                res[i][j] = min(res[i][j], res[i][k] + res[k][j])
    # 負の閉路(いくらでもコストを減らせてしまう場所)がないかチェックする
    for i in range(N):
        if res[i][i] < 0:
            return []
    return res

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

# 全体グラフの最短距離(ここから必要な頂点間だけ使う)
wf = warshall_floyd(N, G)

ans = INF
for r in range(R):
    # TSP(巡回セールスマン)
    dp = list2d(1<<R, R, INF)
    dp[1<<r][r] = 0
    for bit in range(1, (1<<R)-1):
        for i in range(R):
            if not (bit >> i & 1):
                continue
            for j in range(R):
                if bit >> j & 1:
                    continue
                a, b = A[i], A[j]
                dp[bit|1<<j][j] = min(dp[bit|1<<j][j], dp[bit][i] + wf[a][b])
    ans = min(ans, min(dp[-1]))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def main():
    from sys import stdin
    input=stdin.readline
    n, m, r = map(int, input().split())
    root = list(map(int, input().split()))
    abc = [list(map(int, input().split())) for _ in [0]*m]
    inf = 10**10
    dist = [[inf for _ in [0]*n] for _ in [0]*n]
    for i in range(n):
        dist[i][i] = 0
    for a, b, c in abc:
        dist[a-1][b-1] = c
        dist[b-1][a-1] = c
    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]))

    from itertools import permutations

    p = list(permutations(root))

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


main()

Submission status: Time Limit Exceeded

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

  N, M, R= map(int, readline().split())
  r = list(map(int,input().split()))
  lines = readlines()
  edge = np.array([line.split() for line in lines], dtype = np.int64).T
  #print(r)
  #print(edge)
  graph = csr_matrix((edge[2], (edge[:2] - 1)), (N, N))
  ans = float("inf")

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import itertools
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import dijkstra
import sys
readline = sys.stdin.readline
readlines = sys.stdin.readlines

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

for town in itertools.permutations(r,R):
  tmp = 0
  for i in range(R-1):
    distance_mat = dijkstra(graph, directed = False, indices = town[i]-1)
    tmp += distance_mat[town[i+1]-1]
  ans = min(ans,tmp)

print(int(ans))

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

# 各距離を代入する
for i in range(M):
    abc = list(map(int,input().split()))
    a,b,c = abc[0],abc[1],abc[2]
    dist[a][b] = c
    dist[b][a] = c

# Warshall–Floyd Algorithm
for k in range(1,N+1):
    for i in range(1, N+1):
        for j in range(1,N+1):
            if(dist[i][j] > dist[i][k] + dist[k][j]):
                dist[i][j] = dist[i][k] + dist[k][j]

# 各順列について,距離の総和を求める
for dir in itertools.permutations(perm):
    direction = list(dir)
    tmpdir = 0
    for i in range(len(direction) - 1):
        tmpdir += dist[direction[i]][direction[i+1]]
    res = min(tmpdir,res)

print(res)

Submission status: Time Limit Exceeded

Solution code:
# readline比較用

import itertools
import sys
# input = sys.stdin.buffer.readline

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

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

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