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:
import sys
from itertools import permutations

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


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

    A = warshall_floyd(A)

    ans = INF
    for start in r:
        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)

    return ans


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

Submission status: Time Limit Exceeded

Solution code:
import sys
from itertools import permutations

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


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

    A = warshall_floyd(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 += A[s][g]

        ans = min(ans, cur)

    return ans


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

Submission status: Time Limit Exceeded

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.append(b[0])
    return dist
data=dict()
for x in X:
    data[x]=makedist(x)
notvisit=set(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: Time Limit Exceeded

Solution code:
from itertools import permutations as pe
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
for h in range(1,n+1):
    for i in range(1,n+1):
        for j in range(1,n+1):
            if s[i][j]>s[i][h]+s[h][j]:
                s[i][j]=s[i][h]+s[h][j]
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(k)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations as pe
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
for h in range(1,n+1):
    for i in range(1,n+1):
        for j in range(1,n+1):
            if s[i][j]>s[i][h]+s[h][j]:
                s[i][j]=s[i][h]+s[h][j]
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]]
    else:
        k=min(c,k)
print(k)

Submission status: Time Limit Exceeded

Solution code:
def warshall_floyd(d):
    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])
    return d


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

d = [[10*10 for i in range(N)] for i in range(N)] 

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

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

warshall_floyd(d)
ans=10**20
import itertools
for i in itertools.permutations(r):
    s=0
    for z in range(0,len(i)-1):
        s+=d[i[z]-1][i[z+1]-1]
    if(ans>s):
        ans=s
print(ans)

Submission status: Time Limit Exceeded

Solution code:
def permutation(l: list)->list:
    if len(l) == 1:
        return [l]

    ret = []
    for i, e in enumerate(l):
        for p in permutation(l[:i] + l[i+1:]):
            ret.append([e] + p)
    return ret


def joisinos_travel(
        N: int, M: int, R: int, visits: list, edges: list)->int:
    INF = float('inf')

    A = [[INF] * N for _ in range(N)]
    for i in range(N):
        A[i][i] = 0
    for u, v, c in edges:
        A[u-1][v-1] = c
        A[v-1][u-1] = c

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

    min_d = float('inf')
    for perm in permutation(visits):
        d = sum(A[perm[i]-1][perm[i+1]-1] for i in range(R-1))
        min_d = min(min_d, d)

    return min_d


if __name__ == "__main__":
    M = 0
    N, M, R = map(int, input().split())
    visits = [int(s) for s in input().split()]
    edges = [tuple(int(s) for s in input().split()) for _ in range(M)]
    ans = joisinos_travel(N, M, R, visits, edges)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import itertools
def cal(R, c, o):
    return sum([c[R[o[i]] - 1, R[o[i + 1]] - 1]
                for i in range(len(R) - 1)])

n, m, r = list(map(int, input().split()))
R = list(map(int, input().split()))
c = np.array([[1e18] * n] * n)
for _ in range(m):
    a, b, c1 = list(map(int, input().split()))
    a -= 1
    b -= 1
    c[a, b] = c1
    c[b, a] = c1
for k in range(n):
    for i in range(n):
        for j in range(n):
            if c[i, j] > c[i, k] + c[k, j]:
                c[i, j] = c[i, k] + c[k, j]
                c[j, i] = c[i, k] + c[k, j]
order = list(itertools.permutations(range(r)))
ans = min([cal(R, c, i) for i in order])
print(int(ans))

Submission status: Time Limit Exceeded

Solution code:
N,M,R = map(int,input().split())
r = list(map(int,input().split()))
INF = 100000 * N * 10
dp = [[INF for _ in range(N+1)] for _ in range(N+1)]
for _ in range(M):
    a,b,c = map(int,input().split())
    dp[a][b] = c
    dp[b][a] = c
for i in range(N+1):
    dp[i][i] = 0
for k in range(1,N+1):
    for i in range(1,N+1):
        for j in range(1,N+1):
            dp[i][j] = min(dp[i][j],dp[i][k]+dp[k][j])
import itertools
answer = INF
for permutation in itertools.permutations(r,R):
    pathLength = 0
    for i in range(R-1):
        v = permutation[i]
        w = permutation[i+1]
        pathLength += dp[v][w]
    answer = min(pathLength,answer)
print(answer)

Submission status: Time Limit Exceeded

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):
                    dist[i][j] = min(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: Time Limit Exceeded

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, ans = [[10000000 for _ in range(N)] for _ in range(N)], 10000000
    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])
    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)

Submission status: Time Limit Exceeded

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, ans = [[10**9 for _ in range(N)] for _ in range(N)], 10**9
    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])
    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)

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = SR()
    return l
mod = 1000000007

#A

#B

#C
"""
n = I()
d = defaultdict(int)
for i in range(n):
    a = I()
    d[a] ^= 1
d = list(d.values())
print(sum(d))
"""
#D
def dfs(n,k,l,a):
    if n == 0:
        a.append(l)
    for i in range(n):
        dfs(n-1,k[:i]+k[i+1:],l+[k[i]],a)
if __name__ == '__main__':
    n,m,R = LI()
    r = LI()
    f = [i for i in range(n)]
    for i in range(R):
        r[i] -= 1
    v = [[float("inf") for j in range(n)] for i in range(n)]
    for i in range(n):
        v[i][i] = 0
    for i in range(m):
        a,b,c = LI()
        a -= 1
        b -= 1
        v[a][b] = c
        v[b][a] = c
    for k in range(n):
        for i in range(n):
            for j in range(n):
                v[i][j] = min(v[i][j],v[i][k]+v[k][j])
    l = []
    dfs(R,r,[],l)
    ans = float("inf")
    for k in l:
        d = 0
        for i in range(R-1):
            d += v[k[i]][k[i+1]]
        ans = min(ans,d)
    print(ans)
#E

#F

#G

#H

#I

#J

#K

#L

#M

#N

#O

#P

#Q

#R

#S

#T

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = SR()
    return l
mod = 1000000007

#A

#B

#C
"""
n = I()
d = defaultdict(int)
for i in range(n):
    a = I()
    d[a] ^= 1
d = list(d.values())
print(sum(d))
"""
#D
def dfs(n,k,l,a):
    if n == 0:
        a.append(l)
    for i in range(n):
        dfs(n-1,k[:i]+k[i+1:],l+[k[i]],a)
n,m,R = LI()
r = LI()
f = [i for i in range(n)]
for i in range(R):
    r[i] -= 1
v = [[float("inf") for j in range(n)] for i in range(n)]
for i in range(n):
    v[i][i] = 0
for i in range(m):
    a,b,c = LI()
    a -= 1
    b -= 1
    v[a][b] = c
    v[b][a] = c
for k in range(n):
    for i in range(n):
        for j in range(n):
            v[i][j] = min(v[i][j],v[i][k]+v[k][j])
l = []
dfs(R,r,[],l)
ans = float("inf")
for k in l:
    d = 0
    for i in range(R-1):
        d += v[k[i]][k[i+1]]
    ans = min(ans,d)
print(ans)
#E

#F

#G

#H

#I

#J

#K

#L

#M

#N

#O

#P

#Q

#R

#S

#T

Submission status: Time Limit Exceeded

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

Solution code:
from itertools import permutations
N, M, R = map(int, input().split())
rs = permutations(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 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: Time Limit Exceeded

Solution code:
import itertools
N, M, R = map(int, input().split())
rs = list(itertools.permutations(list(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 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: Time Limit Exceeded

Solution code:
import itertools
N, M, R = map(int, input().split())
rs = list(itertools.permutations(list(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 rs:
    t = 0
    for i in range(R-1):
        t += dist[r[i]][r[i+1]]
    ans = min(t, ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
N, M, R = map(int, input().split())
rs = list(itertools.permutations(list(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 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 rs:
    t = 0
    for i in range(R-1):
        t += dist[r[i]][r[i+1]]
    ans = min(t, ans)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import heapq

INF = 100000 * 200 * 10

def warshall(N, ABCs):
    dists = [[INF for _ in range(N)] for __ in range(N)]
    for i in range(N):
        dists[i][i] = 0

    for a, b, c in ABCs:
        dists[a - 1][b - 1] = c
        dists[b - 1][a - 1] = c

    for s in range(N):
        for e in range(N):
            for i in range(N):
                dists[s][e] = min(dists[s][e], dists[s][i] + dists[i][e])
    return dists


def dijkstra(s, e, N, ABCs):
    adjlist = [[] for _ in range(N)]
    for a, b, c in ABCs:
        adjlist[a - 1].append((b, c))
        adjlist[b - 1].append((a, c))

    q = [(0, s)]
    while len(q):
        d, i = heapq.heappop(q)
        if i == e:
            return d
        for nexti, nextd in adjlist[i - 1]:
            heapq.heappush(q, (d + nextd, nexti))
    return None


def dense_dijkstra(s, e, N, ABCs):
    distsmap = [[-1 for _ in range(N)] for __ in range(N)]
    for a, b, c in ABCs:
        distsmap[a - 1][b - 1] = c
        distsmap[b - 1][a - 1] = c

    dists = [INF for _ in range(N)]
    visited = [False for _ in range(N)]
    dists[s - 1] = 0

    while True:
        minW, index = min([(dists[i], i) for i in range(N) if not visited[i]])
        visited[index] = True
        if minW == INF:
            return -1
        if index + 1 == e:
            return minW
        for rindex, w in enumerate(distsmap[index]):
            if w == -1:
                continue
            dists[rindex] = min(dists[rindex], minW + w)

def solve(N, M, R, Rs, ABCs):
    dists = warshall(N, ABCs)
    ans = INF
    for way in permutations(Rs):
        tans = 0
        for s, e in zip(way, way[1:]):
            tans += dists[s - 1][e - 1]
        ans = min(ans, tans)
    return ans


if __name__ == "__main__":
    N, M, R = tuple(map(int, input().split(" ")))
    Rs = list(map(int, input().split(" ")))
    ABCs = [tuple(map(int, input().split(" "))) for _ in range(M)]
    print(solve(N, M, R, Rs, ABCs))

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import heapq

INF = 10 * 10


def warshall(N, ABCs):
    dists = [[INF for _ in range(N)] for __ in range(N)]
    for i in range(N):
        dists[i][i] = 0

    for a, b, c in ABCs:
        dists[a - 1][b - 1] = c
        dists[b - 1][a - 1] = c

    for s in range(N):
        for e in range(N):
            for i in range(N):
                dists[s][e] = min(dists[s][e], dists[s][i] + dists[i][e])
    return dists


def dijkstra(s, e, N, ABCs):
    adjlist = [[] for _ in range(N)]
    for a, b, c in ABCs:
        adjlist[a - 1].append((b, c))
        adjlist[b - 1].append((a, c))

    q = [(0, s)]
    while len(q):
        d, i = heapq.heappop(q)
        if i == e:
            return d
        for nexti, nextd in adjlist[i - 1]:
            heapq.heappush(q, (d + nextd, nexti))
    return None


def dense_dijkstra(s, e, N, ABCs):
    distsmap = [[-1 for _ in range(N)] for __ in range(N)]
    for a, b, c in ABCs:
        distsmap[a - 1][b - 1] = c
        distsmap[b - 1][a - 1] = c

    dists = [INF for _ in range(N)]
    visited = [False for _ in range(N)]
    dists[s - 1] = 0

    while True:
        minW, index = min([(dists[i], i) for i in range(N) if not visited[i]])
        visited[index] = True
        if minW == INF:
            return -1
        if index + 1 == e:
            return minW
        for rindex, w in enumerate(distsmap[index]):
            if w == -1:
                continue
            dists[rindex] = min(dists[rindex], minW + w)


def solve(N, M, R, Rs, ABCs):
    dists = [[-1 for _ in range(N)] for __ in range(N)]
    ans = INF
    for way in permutations(Rs):
        tans = 0
        for s, e in zip(way, way[1:]):
            if dists[s - 1][e - 1] == -1:
                d = dense_dijkstra(s, e, N, ABCs)
                dists[s - 1][e - 1] = d
                dists[e - 1][s - 1] = d
            else:
                d = dists[s - 1][e - 1]
            tans += d
        ans = min(ans, tans)

    return ans


# dists = warshall(N, ABCs)

assert (solve(3, 3, 3, [1, 2, 3], [(1, 2, 1), (2, 3, 1), (3, 1, 4)]) == 2)
assert (solve(3, 3, 2, [1, 3], [(2, 3, 2), (1, 3, 6), (1, 2, 2)]) == 4)
assert (solve(4, 6, 3, [2, 3, 4], [(1, 2, 4), (2, 3, 3), (4, 3, 1), (1, 4, 1), (4, 2, 2), (3, 1, 6)]) == 3)

if __name__ == "__main__":
    N, M, R = tuple(map(int, input().split(" ")))
    Rs = list(map(int, input().split(" ")))
    ABCs = [tuple(map(int, input().split(" "))) for _ in range(M)]
    print(solve(N, M, R, Rs, ABCs))

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import heapq


def warshall(N, ABCs):
    dists = [[100000 * 200 + 1 for _ in range(N)] for __ in range(N)]
    for i in range(N):
        dists[i][i] = 0

    for a, b, c in ABCs:
        dists[a - 1][b - 1] = c
        dists[b - 1][a - 1] = c

    for s in range(N):
        for e in range(N):
            for i in range(N):
                dists[s][e] = min(dists[s][e], dists[s][i] + dists[i][e])
    return dists


def dijkstra(s, e, N, adjlist):
    q = [(0, s)]
    while len(q):
        d, i = heapq.heappop(q)
        if i == e:
            return d
        for nexti, nextd in adjlist[i - 1]:
            heapq.heappush(q, (d + nextd, nexti))
    return None


def solve(N, M, R, Rs, ABCs):
    dists = [[-1 for _ in range(N)] for __ in range(N)]
    adjlist = [[] for _ in range(N)]
    for a, b, c in ABCs:
        adjlist[a - 1].append((b, c))
        adjlist[b - 1].append((a, c))
    ans = 100000 * 200 + 1
    for way in permutations(Rs):
        tans = 0
        for s, e in zip(way, way[1:]):
            if dists[s - 1][e - 1] == -1:
                d = dijkstra(s, e, N, adjlist)
                dists[s - 1][e - 1] = d
                dists[e - 1][s - 1] = d
            else:
                d = dists[s - 1][e - 1]
            tans += d
        ans = min(ans, tans)

    return ans

if __name__ == "__main__":
    N, M, R = tuple(map(int, input().split(" ")))
    Rs = list(map(int, input().split(" ")))
    ABCs = [tuple(map(int, input().split(" "))) for _ in range(M)]
    print(solve(N, M, R, Rs, ABCs))

Submission status: Time Limit Exceeded

Solution code:
def warshall(N, ABCs):
    dists = [[100000 * 200 + 1 for _ in range(N)] for __ in range(N)]
    for i in range(N):
        dists[i][i] = 0

    for a, b, c in ABCs:
        dists[a - 1][b - 1] = c
        dists[b - 1][a - 1] = c

    for s in range(N):
        for e in range(N):
            for i in range(N):
                dists[s][e] = min(dists[s][e], dists[s][i] + dists[i][e])
    return dists


from itertools import permutations


def solve(N, M, R, Rs, ABCs):
    dists = warshall(N, ABCs)
    ans = 100000 * 200 + 1 
    for way in permutations(Rs):
        ans = min(ans, sum([dists[i - 1][j - 1] for i, j in zip(way, way[1:])]))

    return ans


if __name__ == "__main__":
    N, M, R = tuple(map(int, input().split(" ")))
    Rs = list(map(int, input().split(" ")))
    ABCs = [tuple(map(int, input().split(" "))) for _ in range(M)]
    print(solve(N, M, R, Rs, ABCs))

Submission status: Time Limit Exceeded

Solution code:
def warshall(N, ABCs):
    dists = [[10 ** 10 for _ in range(N)] for __ in range(N)]
    for i in range(N):
        dists[i][i] = 0

    for a, b, c in ABCs:
        dists[a - 1][b - 1] = c
        dists[b - 1][a - 1] = c

    for s in range(N):
        for e in range(N):
            for i in range(N):
                dists[s][e] = min(dists[s][e], dists[s][i] + dists[i][e])
    return dists


from itertools import permutations


def solve(N, M, R, Rs, ABCs):
    dists = warshall(N, ABCs)
    ans = 10 ** 10
    for way in permutations(Rs):
        ans = min(ans, sum([dists[i - 1][j - 1] for i, j in zip(way, way[1:])]))

    return ans

if __name__ == "__main__":
    N, M, R = tuple(map(int, input().split(" ")))
    Rs = list(map(int, input().split(" ")))
    ABCs = [tuple(map(int, input().split(" "))) for _ in range(M)]
    print(solve(N, M, R, Rs, ABCs))

Submission status: Time Limit Exceeded

Solution code:
from itertools import*
n,m,R=map(int,input().split())
r=map(int,input().split())
d=[[10**18]*n for _ in range(n)]
for i in range(m):
    a,b,c=map(int,input().split())
    d[a-1][b-1]=c
    d[b-1][a-1]=c
for i in range(n):
    d[i][i]=0
for k in range(n):
    for i in range(n):
        for j in range(n):
            d[i][j]=min(d[i][j],d[i][k]+d[k][j])
m=10**18
for e in permutations(r):
    t=0
    for i,j in zip(e,e[1:]):
        t+=d[i-1][j-1]
    m=min(m,t)
print(m)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n, m, r = map(int, input().split())
rlist = list(map(int, input().split()))
dist = [[-1 for _ in range(n)] for _ in range(n)]
for i in range(n):
  dist[i][i] = 0
abcl = []
for _ in range(m):
  a, b, c = map(int, input().split())
  dist[a-1][b-1] = c
  dist[b-1][a-1] = c

for k in range(0, n):
  for i in range(0, n):
    for j in range(0, n):
      if dist[i][k] != -1 and dist[k][j] != -1:
        if dist[i][j] == -1:
          dist[i][j] = dist[i][k] + dist[k][j]
        elif dist[i][j] > dist[i][k] + dist[k][j]:
          dist[i][j] = dist[i][k] + dist[k][j]

ans = pow(10, 15)
minp = None
for rperm in itertools.permutations(rlist):
  tmp = 0
  tmpp = [rperm[0]-1]
  for pr, nr in zip(rperm, rperm[1:]):
    tmp += dist[pr-1][nr-1]
    tmpp.append(nr-1)
  if ans > tmp:
    ans = tmp
    minp = tmpp
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
inf = float("inf")
n,m,r = map(int,input().split())
ra = list(map(int,input().split()))
dist = [[inf for i in range(n+1)] for i in range(n+1)]
for i in range(m):
    a,b,c = map(int,input().split())
    dist[a][b] = c
    dist[b][a] = c

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

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

ans = inf
for p in itertools.permutations(ra):
    subt = 0
    for i in range(r-1):
        subt += dist[p[i]][p[i+1]]
    if subt < ans:
        ans = subt
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
input = sys.stdin.readline
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,w,R = map(int,input().split())
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(w):
    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 #自身のところに行くコストは０
for i in range(R):
    r[i] -= 1
d = warshall_floyd(d)

res = float("inf")
for v in itertools.permutations(r,R):
    sumd = 0
    for j in range(1,R):
        sumd += d[v[j-1]][v[j]]
    res = min(res,sumd)
print(res)

Submission status: Time Limit Exceeded

Solution code:
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(input())
def S(): return input()
from itertools import permutations
n,m,r=IL()
rl=IL()
for i in range(r):
    rl[i]-=1
cost=[[float("INF") for i in range(n)] for j in range(n)]
for i in range(m):
    f,t,c=IL()
    cost[f-1][t-1]=c
    cost[t-1][f-1]=c
for k in range(n):
    for i in range(n):
        for j in range(n):
            cost[i][j]=min(cost[i][j],cost[i][k]+cost[k][j])

perm=permutations(range(r))
ans=float("INF")
for path in perm:
    t=0
    for i in range(r-1):
        t+=cost[rl[path[i]]][rl[path[i+1]]]
    ans=min(ans,t)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations

N,M,R=map(int,input().split())
*r,=map(int,input().split())
inf=float("inf")
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]=min(d[i][j],d[i][k]+d[k][j])

ans=inf
for i in permutations(r):
    v=0
    for j in range(R-1):
        v+=d[i[j]-1][i[j+1]-1]
    ans=min(ans,v)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
class Solve():
    def __init__(self):
        self.N, self.M, self.R = map(int, input().split())
        self.r = list(map(int, input().split()))
        self.route = [[float('inf') for _ in range(self.N)] for _ in range(self.N)]
        for _ in range(self.M):
            a, b, c = map(int, input().split())
            self.route[a - 1][b - 1] = c
            self.route[b - 1][a - 1] = c
        for i in range(self.N):
            self.route[i][i] = 0

    def WarshallFloid(self):
        for k in range(self.N):
            for i in range(self.N):
                for j in range(self.N):
                    if self.route[i][j] > self.route[i][k] + self.route[k][j]:
                        self.route[i][j] = self.route[i][k] + self.route[k][j]

    def execute(self):
        self.WarshallFloid()
        ans = float('inf')
        checked = set()
        for path in permutations(self.r):
            if tuple(reversed(path)) in checked:
                continue
            checked.add(tuple(reversed(path)))
            temp = 0
            for i in range(self.R - 1):
                temp += self.route[path[i] - 1][path[i + 1] - 1]
            ans = min(ans, temp)
        print(ans)


if __name__ == '__main__':
    Solve().execute()