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:
#!/usr/bin/env python3
import sys
from itertools import permutations

def solve(N: int, M: int, R: int, r: "List[int]", A: "List[int]", B: "List[int]", C: "List[int]"):

    '''
    Warshall-Floyd
    input:  c[|V|][|V|]
            input example to from cost
            (c[i][i] == 0)
    Output: Minimun cost of all paths in the inputed graph 
    '''
    V = N
    INF = 1<<32
    d = [[INF] * (N+1) for i in range(N+1)]

    for i in range(M):
        d[A[i]][B[i]] = C[i]
        d[B[i]][A[i]] = C[i]

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


    ans = INF
    
    for i in permutations(r,len(r)):
        ta = 0
        for x in range(R-1):
            ta += d[i[x]][i[x+1]]
        
        ans = min(ans, ta)
    print(ans)

    return


# Generated by 1.1.5 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)) 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))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, M, R, r, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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


def solve(N: int, M: int, R: int, r: "List[int]", A: "List[int]", B: "List[int]", C: "List[int]"):

    '''
    Warshall-Floyd
    input:  c[|V|][|V|]
            input example to from cost
            (c[i][i] == 0)
    Output: Minimun cost of all paths in the inputed graph 
    '''
    V = N
    INF = 1<<32
    d = [[INF] * (N+1) for i in range(N+1)]

    for i in range(M):
        d[A[i]][B[i]] = C[i]
        d[B[i]][A[i]] = C[i]

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


    ans = INF

    from itertools import permutations
    for i in permutations(r,len(r)):
        ta = 0
        for x in range(R-1):
            ta += d[i[x]][i[x+1]]
        
        ans = min(ans, ta)
    print(ans)

    return


# Generated by 1.1.5 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)) 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))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, M, R, r, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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


def solve(N: int, M: int, R: int, r: "List[int]", A: "List[int]", B: "List[int]", C: "List[int]"):

    '''
    Warshall-Floyd
    input:  c[|V|][|V|]
            input example to from cost
            (c[i][i] == 0)
    Output: Minimun cost of all paths in the inputed graph 
    '''
    V = N
    INF = 1<<32
    d = [[INF] * (N+1) for i in range(N+1)]

    for i in range(M):
        d[A[i]][B[i]] = C[i]
        d[B[i]][A[i]] = C[i]

    for k in range(N+1):
        for i in range(N+1):
            for j in range(N+1):
                if i == j:
                    d[i][j] =0
                else:
                    d[i][j] = min(d[i][j], d[i][k]+d[k][j])


    ans = INF

    from itertools import permutations
    for i in permutations(r,len(r)):
        ta = 0
        for x in range(R-1):
            ta += d[i[x]][i[x+1]]
        
        ans = min(ans, ta)
    print(ans)

    return


# Generated by 1.1.5 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)) 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))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, M, R, r, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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


def solve(N: int, M: int, R: int, r: "List[int]", A: "List[int]", B: "List[int]", C: "List[int]"):

    '''
    Warshall-Floyd
    input:  c[|V|][|V|]
            input example to from cost
            (c[i][i] == 0)
    Output: Minimun cost of all paths in the inputed graph 
    '''
    V = N
    INF = 1<<32
    d = [[INF] * (N+1) for i in range(N+1)]

    for i in range(1, N+1):
        d[i][i] = 0
 
    for i in range(M):
        d[A[i]][B[i]] = C[i]
        d[B[i]][A[i]] = C[i]

    for k in range(N+1):
        for i in range(N+1):
            if d[i][k] == INF : continue
            for j in range(N+1):
                if d[k][j] == INF: continue
                d[i][j] = min(d[i][j], d[i][k]+d[k][j])


    ans = INF

    from itertools import permutations
    for i in permutations(r,len(r)):
        ta = 0
        for x in range(R-1):
            ta += d[i[x]][i[x+1]]
        
        ans = min(ans, ta)
    print(ans)

    return


# Generated by 1.1.5 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)) 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))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, M, R, r, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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


def solve(N: int, M: int, R: int, r: "List[int]", A: "List[int]", B: "List[int]", C: "List[int]"):

    '''
    Warshall-Floyd
    input:  c[|V|][|V|]
            input example to from cost
            (c[i][i] == 0)
    Output: Minimun cost of all paths in the inputed graph 
    '''
    V = N
    INF = 1<<32
    d = [[INF] * (N+1) for i in range(N+1)]

    for i in range(1, N+1):
        d[i][i] = 0
 
    for i in range(M):
        d[A[i]][B[i]] = C[i]
        d[B[i]][A[i]] = C[i]

    for k in range(N+1):
        for i in range(N+1):
            if d[i][k] == INF : continue
            for j in range(N+1):
                if d[k][j] == INF: continue
                d[i][j] = min(d[i][j], d[i][k]+d[k][j])


    ans = INF

    from itertools import product
    for i in product(r,repeat=len(r)):
        # print(i)
        if(len(i) != len(set(i))): continue
        ta = 0
        for j in range(1,len(i)):
            # print(d[i[j-1]][i[j]])
            ta += d[i[j-1]][i[j]]
        
        ans = min(ans, ta)
    
    print(ans)

    return


# Generated by 1.1.5 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)) 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))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, M, R, r, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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


def solve(N: int, M: int, R: int, r: "List[int]", A: "List[int]", B: "List[int]", C: "List[int]"):

    '''
    Warshall-Floyd
    input:  c[|V|][|V|]
            input example to from cost
            (c[i][i] == 0)
    Output: Minimun cost of all paths in the inputed graph 
    '''
    V = N
    INF = 1<<32
    d = [[INF] * (N+1) for i in range(N+1)]

    for i in range(1, N+1):
        d[i][i] = 0
 
    for i in range(M):
        d[A[i]][B[i]] = C[i]
        d[B[i]][A[i]] = C[i]

    for k in range(N+1):
        for i in range(N+1):
            if d[i][k] == INF : continue
            for j in range(N+1):
                if d[k][j] == INF: continue
                d[i][j] = min(d[i][j], d[i][k]+d[k][j])


    ans = INF

    # for i in d:
    #     print(i)

    from itertools import product
    for i in product(r,repeat=len(r)):
        # print(i)
        if(len(i) != len(set(i))): continue
        ta = 0
        for j in range(1,len(i)):
            # print(d[i[j-1]][i[j]])
            ta += d[i[j-1]][i[j]]
        
        ans = min(ans, ta)
    
    print(ans)

    return


# Generated by 1.1.5 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)) 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))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, M, R, r, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq
import bisect

mod = 10**9+7
dd = ((-1,0),(1,0),(0,-1),(0,1))

def I(): return(int(sys.stdin.readline()))
def LI(): return([int(x) for x in sys.stdin.readline().split()])
def S(): return(sys.stdin.readline()[:-1])
def IR(n): return([I() for _ in range(n)])

def GCD(a,b):
    while b!=0:
        a,b = b,a%b
    return a

def LCM(a,b):
    return a * b // GCD(a,b)

def Eratosthenes(N):
    r = [True]*(N+1)
    r[0] = False
    r[1] = False
    i = 2
    while i*i<=N:
        if r[i]: 
            j = i
            while i*j<=N:
                prime[i*j]=False
                j+=1
        i+=1
    return(r)

def main():
    N,M,R = LI()
    r = LI()
    D = [[10**10]*N for _ in range(N)]
    for _ in range(M):
        A,B,C = LI()
        D[A-1][B-1] = C
        D[B-1][A-1] = C
    for i in range(N):
        D[i][i] = 0

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

    ans = 10**11
    for x in range(R**R):
        order = [0] * R
        i = 0
        while x>0:
            order[i] = x%R
            i += 1
            x //= R
        for j in range(1,R):
            for k in range(j):
                if order[j]==order[k]:
                    break
            else:
                continue
            break
        else:
            ans_tmp = 0
            for j in range(R-1):
                ans_tmp += D[r[order[j]]-1][r[order[j+1]]-1]
            ans = min(ans,ans_tmp)
    return(ans)

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

Submission status: Time Limit Exceeded

Solution code:
import sys
import heapq
import bisect

mod = 10**9+7
dd = ((-1,0),(1,0),(0,-1),(0,1))

def I(): return(int(sys.stdin.readline()))
def LI(): return([int(x) for x in sys.stdin.readline().split()])
def S(): return(sys.stdin.readline()[:-1])
def IR(n): return([I() for _ in range(n)])

def GCD(a,b):
    while b!=0:
        a,b = b,a%b
    return a

def LCM(a,b):
    return a * b // GCD(a,b)

def Eratosthenes(N):
    r = [True]*(N+1)
    r[0] = False
    r[1] = False
    i = 2
    while i*i<=N:
        if r[i]: 
            j = i
            while i*j<=N:
                prime[i*j]=False
                j+=1
        i+=1
    return(r)

def main():
    N,M,R = LI()
    r = LI()
    node = [[] for _ in range(N)]
    for _ in range(M):
        a,b,c = LI()
        node[a-1].append([b-1,c])
        node[b-1].append([a-1,c])

    dic = {}
    for x in r:
        dic_part = {}
        for y in r:
            dic_part[y-1] = 0
        dic[x-1] = dic_part

    for x in r:
        ques = []
        flag = [True] * len(node)
        heapq.heappush(ques,[0,x-1])
        while ques:
            dist,crt = heapq.heappop(ques)
            if flag[crt]:
                flag[crt] = False
                if (crt+1) in r:
                    dic[x-1][crt] = dist
                    dic[crt][x-1] = dist
                for nxt,nxt_dist in node[crt]:
                    if flag[nxt]:
                        heapq.heappush(ques,[dist+nxt_dist,nxt])
    ans = 10**11
    for x in range(R**R):
        order = [0] * R
        i = 0
        while x>0:
            order[i] = x%R
            i += 1
            x //= R
        for j in range(1,R):
            for k in range(j):
                if order[j]==order[k]:
                    break
            else:
                continue
            break
        else:
            ans_tmp = 0
            for j in range(R-1):
                ans_tmp += dic[r[order[j]]-1][r[order[j+1]]-1]
            ans = min(ans,ans_tmp)
    return(ans)



    



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

Submission status: Time Limit Exceeded

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

ans=3000000000

def permu(ju,now,su,co):
    if now==0:
        global ans
        ans=min(ans,su)
        return
    else:
        for i in range(r):
            if ju[i]:
                ju[i]=False
                su+=dp[co][rute[i]-1]
                permu(ju,now-1,su,rute[i]-1)
                ju[i]=True
                su-=dp[co][rute[i]-1]
    return

rute=list(map(int,input().split()))
dp=[[30000000 for i in range(n)] for i in range(n)]
for i in range(n):
    dp[i][i]=0
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):
    for j in range(n):
        for k in range(n):
            dp[j][k]=min(dp[j][i]+dp[i][k],dp[j][k])


ju=[True for i in range(r)]
for i in range(r):
    ju[i]=False
    permu(ju,r-1,0,rute[i]-1)
    ju[i]=True
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

def WarshallFloyd(M):
    N = len(M)
    for k in range(N):
        for j in range(N):
            for i in range(N):
                M[i][j] = min(M[i][j], M[i][k] + M[k][j])
    return M

INF = 1e10

N, M, K = map(int, input().split())
R = [int(i) - 1 for i in input().split()]
E = [[INF] * N for _ in range(N)]
for a, b, c in (map(int, input().split()) for _ in range(M)):
    a -= 1; b -= 1
    E[a][b] = E[b][a] = c

E = WarshallFloyd(E)
ans = min(sum(E[p[i]][p[i + 1]] for i in range(K - 1)) for p in permutations(R))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import*;N,M,R=map(int,input().split())
r=map(int,input().split());G=[[9e9]*N for _ in[0]*N]
for _ in[0]*M:A,B,C=map(int,input().split());G[A-1][B-1]=G[B-1][A-1]=C
for i in range(N):
 for j in range(N):
  for k in range(N):G[j][k]=min(G[j][k],G[j][i]+G[i][k])
print(min(sum(G[i-1][j-1]for i,j in zip(t,t[1:]))for t in permutations(r)))

Submission status: Time Limit Exceeded

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


def warshall_floyd(D, 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])


def main():
    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(N):
        D[i][i] = 0
    for _ in range(M):
        a, b, c = map(int, input().split())
        D[a-1][b-1] = c
        D[b-1][a-1] = c

    warshall_floyd(D, N)

    ans = float('inf')
    for P in itertools.permutations(r):
        cost = 0
        for i in range(R-1):
            cost += D[P[i]-1][P[i+1]-1]
        ans = min(ans, cost)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import itertools

def warshall_floyd(D, 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])


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(N):
    D[i][i] = 0
for _ in range(M):
    a, b, c = map(int, input().split())
    D[a-1][b-1] = c
    D[b-1][a-1] = c

warshall_floyd(D, N)

ans = float('inf')
for P in itertools.permutations(r):
    cost = 0
    for i in range(R-1):
        cost += D[P[i]-1][P[i+1]-1]
    ans = min(ans, cost)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
def warshal_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(int, input().split()))
R = [r_-1 for r_ in R]

d = [[float('inf') for i in range(n)] for j in range(n)]

for i in range(m):
  x, y, z = map(int, input().split())
  x, y = x-1, y-1
  d[x][y] = z
  d[y][x] = z
  
for i in range(n):
  d[i][i] = 0

d = warshal_floyd(d)

import itertools
ans = float('inf')
for p in itertools.permutations(R):
  q = 0
  for i in range(len(p)-1):
    q += d[p[i]][p[i+1]]
  if q <= ans:
    ans = q
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

dist = [[float('inf')] * N for _ in range(N)]
for _ in range(M):
	a, b, c = map(int, input().split())
	a -= 1
	b -= 1
	dist[a][b] = dist[b][a] = 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])

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

Submission status: Time Limit Exceeded

Solution code:
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 _ in range(M):
	tmp = list(map(int, input().split()))
	dist[tmp[0] - 1][tmp[1] - 1] = dist[tmp[1] - 1][tmp[0] - 1] = tmp[2]

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 = float('inf')
seen = []
def DFS():
	global ans
	for i in range(len(r)):
		if i not in seen:
			seen.append(i)
			if len(seen) == len(r):
				sumDist = 0
				for j in range(len(seen) - 1):
					sumDist += dist[r[seen[j]]][r[seen[j+1]]]
				ans = min(ans, sumDist)
			else:
				DFS()
			del seen[-1]

DFS()
print(ans)

Submission status: Time Limit Exceeded

Solution code:
'''
ワーシャルフロイド法
例題:https://atcoder.jp/contests/abc073/tasks/abc073_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 _ in range(M):
	tmp = list(map(int, input().split()))
	dist[tmp[0] - 1][tmp[1] - 1] = dist[tmp[1] - 1][tmp[0] - 1] = tmp[2]

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 = float('inf')
seen = []
def DFS():
	global ans
	for i in range(len(r)):
		if r[i] not in seen:
			seen.append(r[i])
			if len(seen) == len(r):
				sumDist = 0
				for j in range(len(seen) - 1):
					sumDist += dist[seen[j]][seen[j+1]]
				ans = min(ans, sumDist)
			else:
				DFS()
			del seen[-1]

DFS()
print(ans)

Submission status: Time Limit Exceeded

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

def WarshallFloyd(V: int, cost: "List[List[int]]"):
    """
    全ての頂点対の間の最短距離を求めます。
    ==============
    V: 頂点数
    cost: 隣接行列(辺が存在しない部分はINF)
    --------------
    cost: 最短距離の行列
    """
    for k in range(V):
        for i in range(V):
            for j in range(V):
                cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j])
    return cost

def solve(N: int, M: int, R: int, r: "List[int]", A: "List[int]", B: "List[int]", C: "List[int]"):
    INF = 1e18
    G = [[INF for _ in range(N)] for _ in range(N)]
    for i in range(M):
        G[A[i]-1][B[i]-1] = C[i]
        G[B[i]-1][A[i]-1] = C[i]
    cost = WarshallFloyd(N, G)
    mn = 1e18
    for p in itertools.permutations(r):
        path = 0
        for i in range(R-1):
            path += cost[p[i+1]-1][p[i]-1]
        mn = min(path, mn)
    print(mn)
    return


# Generated by 1.1.5 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)) 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))
        B[i] = int(next(tokens))
        C[i] = int(next(tokens))
    solve(N, M, R, r, A, B, C)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict, deque
from itertools import permutations
inf = float('inf')

def min_dis_dfs(graph, start_node, end_node):
  stack = deque()
  stack.append([start_node,0])
  done = []
  min_dis = inf
  
  while len(stack) > 0:
    prv_node, prv_dis = stack.pop()
    #print('#'*20)
    #print("prv_node:{}, prv_dis:{}".format(prv_node, prv_dis))
    for node, dis in graph[prv_node]:
      if node not in done:
        if node == end_node and min_dis > prv_dis + dis:min_dis=prv_dis + dis
        else:
          done.append(node)
          stack.append([node,prv_dis + dis])
      #print('node:{}, min_dis:{}, dis:{}'.format(node, min_dis, dis))
  return min_dis
  
n,m,r =map(int,input().split())
rlist = [int(r)-1 for r in input().split()]
graph = defaultdict(list)

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

ans = inf
for r_case in permutations(rlist, r):
  dis = 0
  for i in range(r-1):
    dis += min_dis_dfs(graph, r_case[i], r_case[i+1])
  if ans > dis:ans = dis
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

class WarshallFloyd(object):

    def __init__(self, adj):
        """
        ワーシャル・フロイド法によって全頂点間の最短距離を O(|V|^3) で計算する。

        :param adj: 隣接行列 adj[i][j] でi番目の頂点からj番目の頂点へのコストを示す パスがなければINF
        """
        self._dist = adj  # 各頂点間の最短距離 初期値として隣接行列をそのまま用い、[i, i]要素を0に初期化する
        for i in range(len(adj)):
            self._dist[i][i] = 0

        self._solve()

    def _solve(self):
        v_len = len(self._dist)
        for i in range(v_len):  # 経由する頂点
            for j in range(v_len):  # 開始頂点
                for k in range(v_len):  # 終端
                    self._dist[j][k] = min(self._dist[j][k], self._dist[j][i] + self._dist[i][k])

    def distance(self, start, goal):
        return self._dist[start][goal]

    def path(self, start, goal):
        pass


N, M, R = map(int, input().split())
r = list(map(int, input().split()))
adj = [[float('inf') for _ in range(N + 1)] for _ in range(N + 1)]
for _ in range(M):
    A, B, C = map(int, input().split())
    adj[A][B] = C
    adj[B][A] = C

wf = WarshallFloyd(adj)

ans = float('inf')
tours = list(map(list, permutations(r, R)))
for tour in tours:
    cost = 0
    for i in range(1, len(tour)):
        cost += wf.distance(tour[i - 1], tour[i])
    ans = min(ans, cost)
print(ans)

Submission status: Time Limit Exceeded

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

M = [[float("inf")] * (n+1) for i in range(n+1)]

for i in range(1, n+1):
    M[i][i] = 0
for i in range(m):
    M[A[i][0]][A[i][1]] = A[i][2]
    M[A[i][1]][A[i][0]] = A[i][2]

for k in range(1, n+1):
    for i in range(1, n+1):
        for j in range(i+1, n+1):
            if k <= i:
                M[i][j] = min(M[i][j], M[k][i] + M[k][j])
            elif k <= j:
                M[i][j] = min(M[i][j], M[i][k] + M[k][j])
            else:
                M[i][j] = min(M[i][j], M[i][j] + M[j][k])

# 上のコードだとTLE

# from scipy.sparse.csgraph import floyd_warshall
# M = floyd_warshall(M)

import itertools
R1 = list(itertools.permutations(R))

ans = float("inf")
for i in range(len(R1)):
    ans1 = 0
    for j in range(r-1):
        ans1 += M[R1[i][j]][R1[i][j+1]]
    ans = min(ans, ans1)

print(int(ans))

Submission status: Time Limit Exceeded

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

M = [[float("inf")] * (n+1) for i in range(n+1)]

for i in range(1, n+1):
    M[i][i] = 0
for i in range(m):
    M[A[i][0]][A[i][1]] = A[i][2]
    M[A[i][1]][A[i][0]] = A[i][2]

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

# 上のコードだとTLE

# from scipy.sparse.csgraph import floyd_warshall
# M = floyd_warshall(M)

import itertools
R1 = list(itertools.permutations(R))

ans = float("inf")
for i in range(len(R1)):
    ans1 = 0
    for j in range(r-1):
        ans1 += M[R1[i][j]][R1[i][j+1]]
    ans = min(ans, ans1)

print(int(ans))

Submission status: Time Limit Exceeded

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

M = [[float("inf")] * (n+1) for i in range(n+1)]

for i in range(1, n+1):
    M[i][i] = 0
for i in range(m):
    M[A[i][0]][A[i][1]] = A[i][2]
    M[A[i][1]][A[i][0]] = A[i][2]

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

import itertools
R1 = list(itertools.permutations(R))

ans = float("inf")
for i in range(len(R1)):
    ans1 = 0
    for j in range(r-1):
        ans1 += M[R1[i][j]][R1[i][j+1]]
    ans = min(ans, ans1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

inf = float("inf")

N, M, R = map(int, input().split())
r = [int(s) - 1 for s in input().split()]
d = [[inf] * 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
for k in range(N):
    for i in range(N):
        for j in range(N):
            d[i][j] = d[j][i] = min(d[i][j], d[i][k] + d[k][j])
ans = min([sum([d[r[p[i]]][r[p[i+1]]] for i in range(R-1)])
           for p in permutations(range(R))])
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, M, R = map(int, input().split())
Rs = list(map(int, input().split()))

INF = 100000*200*200
dp = [[INF for _ in range(N)] for _ in range(N)]
for _ 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):
    for j in range(N):
        for k in range(N):
            dp[j][k] = min(dp[j][k], dp[j][i]+dp[i][k])


def ind(i, R, rem, l, ans):
    if i == R:
        ans.append(l)
        return ans
    for r in rem:
        nl = l[:]
        nl.append(r)
        nr = rem[:]
        nr.remove(r)
        ans = ind(i+1, R, nr, nl, ans)
    return ans

inds = ind(0, R, [i for i in range(R)], [], [])

for k, ind in enumerate(inds):
    D = 0
    for j in range(R-1):
        D += dp[Rs[ind[j]]-1][Rs[ind[j+1]]-1]
    if k == 0:
        ans = D
    ans = min(ans, D)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N, M, R = map(int,input().split())
r = list(map(int,input().split()))
ABC = [list(map(int,input().split())) for _ in range(M)]

inf = int(1e9+7)
costs = [[inf if i != j else 0 for j in range(N+5)]for i in range(N+5)]

for a, b, c in ABC:
  if costs[a][b] > c:
    costs[a][b] = costs[b][a] = c

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

from itertools import permutations

ans = inf
for per in permutations(r):
  tmp = 0
  for i in range(R-1):
    tmp += costs[per[i]][per[i+1]]
  ans = min(ans, tmp)
print(ans)