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

    def WFInitialize(self):
        for i in range(self.N):
            # self.dist[i][i] = 0
            self.route[i][i] = 0

    def WarshallFloid(self):
        self.WFInitialize()
        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')
        for path in permutations(self.r):
            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()

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

    def WFInitialize(self):
        self.dist = [[float('inf') for _ in range(self.N)] for _ in range(self.N)]
        for i in range(self.N):
            for j in range(self.N):
                if self.dist[i][j] is not float('inf'):
                    self.dist[i][j] = self.route[i][j]
        for i in range(self.N):
            self.dist[i][i] = 0

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

    def execute(self):
        self.WarshallFloid()
        ans = float('inf')
        perm = permutations(self.r)
        for path in perm:
            temp = 0
            for i in range(self.R - 1):
                temp += self.dist[path[i] - 1][path[i + 1] - 1]
            ans = min(ans, temp)
        print(ans)


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

Submission status: Time Limit Exceeded

Solution code:
n, m, r = map(int,input().split())
rs = list(map(int, input().split()))
distance = [[float("inf")]*n for i in range(n)]
for i in range(n):
    distance[i][i] = 0
for i in range(m):
    a, b, c = list(map(int, input().split()))
    a, b = a-1, b-1
    distance[a][b] = c
    distance[b][a] = c

# 全点間最短距離を求める
for k in range(n):
    for i in range(n):
        for j in range(n):
            distance[i][j] = min(distance[i][j],distance[i][k] + distance[k][j])
# r個の並びを考える
from itertools import permutations
ans = float("inf")

for v in permutations(rs, len(rs)):
    dist_tmp = 0
    for i in range(r-1):
        dist_tmp += distance[v[i]-1][v[i+1]-1]
    ans = min(ans, dist_tmp)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
N, M, R = map(int, input().split())
r = tuple(map(lambda n: int(n)-1, input().split()))
inf = float("inf")
vertices = [[inf]*N for _ in [0]*N]
for _ in [0]*M:
    a, b, c = map(int, input().split())
    vertices[a-1][b-1] = c
    vertices[b-1][a-1] = c

for k in range(N):
    for i in range(N):
        c2 = vertices[i][k]
        for j, (c1, c3) in enumerate(zip(vertices[i], vertices[k])):
            vertices[i][j] = c1 if c1 < c2+c3 else c2+c3

ans = inf

for p in itertools.permutations(r):
    subt = 0
    for i in range(R-1):
        subt += vertices[p[i]][p[i+1]]
    if subt < ans:
        ans = subt

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
import heapq as hq
from itertools import permutations
def dijkstra(E, D, start,W):
    q = []
    V = [-1]*N
    V[start] = 0
    for i in range(start):
        V[i] = W[i][start]
        for e in E[i]:
            if e > start:
                hq.heappush(q, (V[i] + D[(i,e)], e))
    for e in E[start]:
        if V[e] == -1:
            hq.heappush(q, (D[start, e],e))
    # print(V, q)
    while q:
        d, v = hq.heappop(q)
        if V[v] >= 0:
            continue
        V[v] = d
        for e in E[v]:
            if V[e] == -1:
                hq.heappush(q, (D[v,e]+d, e))
    return V
N, M, r = map( int, input().split())
R = list( map( int, input().split()))
d = defaultdict( int)
E = [ [] for _ in range(N)]
for _ in range(M):
    a, b, c = map( int, input().split())
    a, b = a-1, b-1
    d[(a,b)] = d[(b,a)] = c
    E[a].append(b)
    E[b].append(a)
W = [ [-1]*N for i in range(N)]
for i in range(N):
    W[i] = dijkstra(E,d,i,W)
    # print(W)
ans = 10**9
for P in permutations( range(r)):
    now = R[P[0]]-1
    cans = 0
    for i in range(1,r):
        cans += W[now][R[P[i]]-1]
        now = R[P[i]]-1
    if cans < ans:
        ans = cans
print( ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
import heapq as hq
from itertools import permutations
def dijkstra(E, D, start):
    q = []
    V = [-1]*N
    V[start] = 0
    for e in E[start]:
        hq.heappush(q, (D[start, e],e))
    while q:
        d, v = hq.heappop(q)
        if V[v] >= 0:
            continue
        V[v] = d
        for e in E[v]:
            if V[e] == -1:
                hq.heappush(q, (D[v,e]+d, e))
    return V
N, M, r = map( int, input().split())
R = list( map( int, input().split()))
d = defaultdict( int)
E = [ [] for _ in range(N)]
for _ in range(M):
    a, b, c = map( int, input().split())
    a, b = a-1, b-1
    d[(a,b)] = d[(b,a)] = c
    E[a].append(b)
    E[b].append(a)
W = [ dijkstra(E,d,i) for i in range(N)]
ans = 10**9
for P in permutations( range(r)):
    now = R[P[0]]-1
    cans = 0
    for i in range(1,r):
        cans += W[now][R[P[i]]-1]
        now = R[P[i]]-1
    if cans < ans:
        ans = cans
print( ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
import heapq as hq
from itertools import permutations
def dijkstra(E, D, start):
    q = []
    V = [-1]*N
    V[start] = 0
    for e in E[start]:
        hq.heappush(q, (D[start, e],e))
    while q:
        d, v = hq.heappop(q)
        if V[v] >= 0:
            continue
        V[v] = d
        for e in E[v]:
            if V[e] == -1:
                hq.heappush(q, (D[v,e]+d, e))
    return V
N, M, r = map( int, input().split())
R = list( map( int, input().split()))
d = defaultdict( int)
E = [ [] for _ in range(N)]
for _ in range(M):
    a, b, c = map( int, input().split())
    a, b = a-1, b-1
    d[(a,b)] = d[(b,a)] = c
    E[a].append(b)
    E[b].append(a)
W = [ dijkstra(E,d,i) for i in range(N)]
ans = 10**9
for P in permutations( range(r)):
    now = R[P[0]]-1
    cans = 0
    for i in range(1,r):
        cans += W[now][R[P[i]]-1]
        now = R[P[i]]-1
    if cans < ans:
        ans = cans
print( ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq
import itertools
n,m,R=map(int,input().split())
r=list(map(int,input().split()))
edges=[[] for _ in range(n)]
for _ in range(m):
    a,b,c = map(int, input().split())
    a,b=a-1,b-1
    edges[a].append((b, c))
    edges[b].append((a, c))

def dijkstra(x,route):
    d=[float('inf')]*n
    d[x]=0
    visited={x}
    hq=[(0,x)]
    while hq:
        u=heapq.heappop(hq)[1]
        visited.add(u)
        for node, cost in route[u]:
            if (node not in visited) and d[node]>d[u]+cost:
                d[node]=d[u]+cost
                heapq.heappush(hq,(d[node],node))
    return d
dist=[[] for _ in range(n)]
for i in range(n):
    dist[i]=dijkstra(i,edges)
ans=float("inf")
t=itertools.permutations(r)
for i in t:
    d=0
    start=i[0]-1
    for end in i[1:]:
        d+=dist[start][end-1]
        start=end-1
    ans=min(ans,d)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import heapq
import itertools
n,m,R=map(int,input().split())
r=list(map(int,input().split()))
edges=[[] for _ in range(n)]
for _ in range(m):
    a,b,c = map(int, input().split())
    a,b=a-1,b-1
    edges[a].append((b, c))
    edges[b].append((a, c))

def dijkstra(x,route):
    d=[float('inf')]*n
    d[x]=0
    visited={x}
    hq=[(0,x)]
    while hq:
        u=heapq.heappop(hq)[1]
        visited.add(u)
        for node, cost in route[u]:
            if (node not in visited) and d[node]>d[u]+cost:
                d[node]=d[u]+cost
                heapq.heappush(hq,(d[node],node))
    return d
dist=[[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
    dist[i]=dijkstra(i,edges)
ans=float("inf")
t=itertools.permutations(r)
for i in t:
    d=0
    start=i[0]-1
    for end in i[1:]:
        d+=dist[start][end-1]
        start=end-1
    ans=min(ans,d)
print(ans)

Submission status: Time Limit Exceeded

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

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

dist=WarshallFloyd(dist)
ans=float("inf")
t=itertools.permutations(r)
for i in t:
    d=0
    start=i[0]-1
    for end in i[1:]:
        d+=dist[start][end-1]
        start=end-1
    ans=min(ans,d)
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n,m,R = map(int,input().split())
r = list(map(int,input().split()))
dis = [[float('inf')]*(n) for _ in range(n)]

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

for i in range(n):
    dis[i][i] = 0

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

mindis = float('inf')
for p in itertools.permutations(r):
    total = 0
    for i in range(R-1):
        total += dis[p[i]-1][p[i+1]-1]
        
    mindis = min(mindis,total)
    
print(mindis)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n,m,R = map(int,input().split())
r = list(map(int,input().split()))
dis = [[float('inf')]*(n) for _ in range(n)]

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

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

mindis = float('inf')
for p in itertools.permutations(r):
    total = 0
    for i in range(R-1):
        total += dis[p[i]-1][p[i+1]-1]
        
    mindis = min(mindis,total)
    
print(mindis)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n,m,R = map(int,input().split())
r = list(map(int,input().split()))
dis = [[float('inf')]*(n) for _ in range(n)]

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

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

mind = []
for p in itertools.permutations(r):
    total = 0
    for i in range(R-1):
        total += dis[p[i]-1][p[i+1]-1]

    mind.append(total)
    
print(min(mind))

Submission status: Time Limit Exceeded

Solution code:
import itertools

n,m,R = map(int,input().split())
r = list(map(int,input().split()))
dis = [[float('inf')]*(n) for _ in range(n)]

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

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

p = list(itertools.permutations(r))
mind = []
for t in p:
    total = 0
    for i in range(R-1):
        total += dis[t[i]-1][t[i+1]-1]

    mind.append(total)
    
print(min(mind))

Submission status: Time Limit Exceeded

Solution code:
import itertools
def warshall_floyd(n,d):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k]+d[k][j])
    return d
            
N,M,R = list(map(int,input().split()))
r = [i-1 for i in list(map(int,input().split()))]
data = [list(map(int,input().split())) for i in range(M)]
root = list(itertools.permutations(r,R))

#ワ―シャルフロイド
d = [[float('inf') for j in range(N)] for i in range(N)]
for s in data:
     d[s[0]-1][s[1]-1]=s[2]
     d[s[1]-1][s[0]-1]=s[2]
for i in range(N):
    d[i][i] = 0
d = warshall_floyd(N,d)


ans = float('inf')
#経路を全部試す
for s in root:
    root_sum = 0
    for t in range(1,R):
        root_sum += d[s[t-1]][s[t]]
    ans = min(root_sum,ans)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, m, r = list(map(int, input().split()))
rs = list(map(int, input().split()))
# construct map
import numpy as np
dists = np.ones((n + 1, n + 1)) * float('inf')
for _ in range(m):
    a, b, c = list(map(int, input().split()))
    dists[a, b] = dists[b, a] = c
for i in range(1, n + 1):
    dists[i, i] = 0

from itertools import product, permutations
for i, j in product(range(1, 1 + n), repeat=2):
    for k in range(j + 1, n + 1):
        dists[j, k] = dists[k, j] = min(dists[j, k], dists[j, i] + dists[i, k])

ans = float('inf')
for path in permutations(rs):
    val = sum(dists[i, j] for i, j in zip(path, path[1:]))
    val = int(val)
    if val < ans:
        ans = val

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, m, r = list(map(int, input().split()))
rs = list(map(int, input().split()))
# construct map
import numpy as np
dists = np.ones((n + 1, n + 1)) * float('inf')
for _ in range(m):
    a, b, c = list(map(int, input().split()))
    dists[a, b] = dists[b, a] = c
for i in range(1, n + 1):
    dists[i, i] = 0

from itertools import product, permutations
for i, j in product(range(1, 1 + n), repeat=2):
    for k in range(j + 1, n + 1):
        if dists[j, k] > dists[j, i] + dists[i, k]:
            dists[j, k] = dists[k, j] = dists[j, i] + dists[i, k]

ans = float('inf')
for path in permutations(rs):
    val = sum(dists[i, j] for i, j in zip(path, path[1:]))
    val = int(val)
    if val < ans:
        ans = val

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, m, r = list(map(int, input().split()))
rs = list(map(int, input().split()))
# construct map
import numpy as np
dists = np.ones((n + 1, n + 1)) * float('inf')
for _ in range(m):
    a, b, c = list(map(int, input().split()))
    dists[a, b] = dists[b, a] = c

from itertools import product, permutations
for i, j in product(range(1, 1 + n), repeat=2):
    for k in range(j + 1, n + 1):
        if dists[j, k] > dists[j, i] + dists[i, k]:
            dists[j, k] = dists[k, j] = dists[j, i] + dists[i, k]

ans = float('inf')
for path in permutations(rs):
    val = sum(dists[i, j] for i, j in zip(path, path[1:]))
    val = int(val)
    if val < ans:
        ans = val

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, m, r = list(map(int, input().split()))
rs = list(map(int, input().split()))
# construct map
import numpy as np
dists = np.ones((n + 1, n + 1)) * float('inf')
for _ in range(m):
    a, b, c = list(map(int, input().split()))
    dists[a, b] = dists[b, a] = c

from itertools import product, permutations
for i, j, k in product(range(1, 1 + n), repeat=3):
    if dists[j, k] > dists[j, i] + dists[i, k]:
        dists[j, k] = dists[k, j] = dists[j, i] + dists[i, k]

ans = float('inf')
for path in permutations(rs):
    val = sum(dists[i, j] for i, j in zip(path, path[1:]))
    val = int(val)
    if val < ans:
        ans = val

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, m, r = list(map(int, input().split()))
rs = list(map(int, input().split()))
# construct map
import numpy as np
dists = np.ones((n + 1, n + 1)) * float('inf')
for _ in range(m):
    a, b, c = list(map(int, input().split()))
    dists[a, b] = dists[b, a] = c

from itertools import product, permutations
for i, j, k in product(range(1, 1 + n), repeat=3):
    if dists[j, k] > dists[j, i] + dists[i, k]:
        dists[j, k] = dists[j, i] + dists[i, k]

ans = float('inf')
for path in permutations(rs):
    val = sum(dists[i, j] for i, j in zip(path, path[1:]))
    val = int(val)
    if val < ans:
        ans = val

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, m, r = list(map(int, input().split()))
rs = set(map(int, input().split()))
abcs = []
for _ in range(m):
    abcs.append(list(map(int, input().split())))

# construct graph
roads = [[] for _ in range(n + 1)]
for a, b, c in abcs:
    roads[a].append((b, c))
    roads[b].append((a, c))
# road from sky
for rr in rs:
    roads[0].append((rr, 0))

import heapq
import copy
# distance, town, rest-town-list, walked
Q = [(0, 0, rs, set())]
while len(Q) > 0:
    d, u, rest, walked = heapq.heappop(Q)
    if len(rest) == 0:
        ans = d
        break
    for v, dd in roads[u]:
        if (u, v) not in walked:
            heapq.heappush(Q, (d + dd, v, rest - {v}, walked | {(u, v)}))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
n, m, r = list(map(int, input().split()))
rs = set(map(int, input().split()))
abcs = []
for _ in range(m):
    abcs.append(list(map(int, input().split())))

# construct graph
roads = [[] for _ in range(n + 1)]
for a, b, c in abcs:
    roads[a].append((b, c))
    roads[b].append((a, c))
# road from sky
for rr in rs:
    roads[0].append((rr, 0))

import heapq
import copy
# distance, town, rest-town-list
Q = [(0, 0, rs)]
while len(Q) > 0:
    d, u, rest = heapq.heappop(Q)
    if len(rest) == 0:
        ans = d
        break
    for v, dd in roads[u]:
        heapq.heappush(Q, (d + dd, v, rest - {v}))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import sys


input = sys.stdin.readline


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

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


def war(mat):
    ran = range(N)
    for i in ran:
        for j in ran:
            for k in ran:
                mat[j][k] = min(mat[j][k], mat[j][i]+mat[i][k])
    return mat


ans = inf
mat = war(mat)
for l in permutations(dest):
    tmp = 0
    for u, v in zip(l, l[1:]):
        tmp += mat[u][v]
        if tmp > ans:
            break
    ans = min(ans, tmp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import sys


input = sys.stdin.readline


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

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


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


ans = inf
for l in permutations(dest):
    tmp = 0
    for u, v in zip(l, l[1:]):
        tmp += mat[u][v]
        if tmp > ans:
            break
    ans = min(ans, tmp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import sys


input = sys.stdin.readline


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

dest = [x-1 for x in map(int, input().split())]


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


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


ans = inf
for l in permutations(dest):
    tmp = 0
    for u, v in zip(l, l[1:]):
        tmp += mat[u][v]
        if tmp > ans:
            break
    ans = min(ans, tmp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import sys


input = sys.stdin.readline


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

dest = [x-1 for x in map(int, input().split())]


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


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


ans = inf
for l in permutations(dest):
    tmp = 0
    for u, v in zip(l, l[1:]):
        tmp += mat[u][v]
    ans = min(ans, tmp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n, m, R = map(int, input().split())
r = list(map(int, input().split()))
dis = [[float("inf") for _ in range(n)] for _ in range(n)]
for _ in range(m):
    a, b, c = map(int, input().split())
    dis[a - 1][b - 1] = c
    dis[b - 1][a - 1] = c

for k in range(n):
    for i in range(n):
        for j in range(n):
            if dis[i][j] > dis[i][k] + dis[k][j]:
                dis[i][j] = dis[i][k] + dis[k][j]


_min = float("inf")
it = itertools.permutations(r)
for iterR in it:
    _dis = 0
    start = iterR[0] - 1
    for end in iterR[1:]:
        _dis += dis[start][end - 1]
        start = end - 1
    _min = min(_min, _dis)
print(_min)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import sys


input = sys.stdin.readline


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

#dest = (list)(map(lambda x: (int)(x)-1, input().split()))
dest = [x-1 for x in map(int, input().split())]


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


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


ans = inf
for l in permutations(dest):
    tmp = 0
    for u, v in zip(l, l[1:]):
        tmp += mat[u][v]
    ans = min(ans, tmp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n, m, R = map(int, input().split())
r = list(map(int, input().split()))
dis = [[float("inf") for _ in range(n)] for _ in range(n)]
for _ in range(m):
    a, b, c = [int(i) for i in input().split()]
    dis[a - 1][b - 1] = c
    dis[b - 1][a - 1] = c

# 全ての頂点間の最短距離を算出、
for k in range(n):
    for i in range(n):
        for j in range(n):
            if dis[i][j] > dis[i][k] + dis[k][j]:
                dis[i][j] = dis[i][k] + dis[k][j]


_min = float("inf")
it = itertools.permutations(r)
for iterR in it:
    _dis = 0
    start = iterR[0] - 1
    for end in iterR[1:]:
        _dis += dis[start][end - 1]
        start = end - 1
    _min = min(_min, _dis)
print(_min)

"""
print("2 vs "+func(3, 3, [0, 1, 2], [[0, 1, 4], [1, 0, 1], [4, 1, 0]]))
print("4 vs "+func(3, 3, [0, 2], [[0, 2, 6], [2, 0, 2], [6, 2, 0]]))
print("3 vs "+func(4, 6, [1, 2, 3], [[0, 4, 6, 1], [4, 0, 3, 2], [6, 3, 0, 1], [1, 2, 1, 0]]))
# print("print(func({}, {}, {}, {}))".format(n, m, r, adj))
"""

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations as perm
import sys


input = sys.stdin.readline


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

dest = (list)(map(lambda x: (int)(x)-1, input().split()))


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


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


ans = inf
for l in perm(dest):
    tmp = 0
    for u,v in zip(l,l[1:]):
        tmp += mat[u][v]
    ans = min(ans, tmp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n, m, R = [int(i) for i in input().split()]
r = [int(i) - 1 for i in input().split()]
dis = [[float("inf") for _ in range(n)] for _ in range(n)]
for i in range(m):
    a, b, c = [int(i) for i in input().split()]
    dis[a - 1][b - 1] = c
    dis[b - 1][a - 1] = c

# 全ての頂点間の最短距離を算出、
for k in range(n):
    for i in range(n):
        for j in range(n):
            if dis[i][j] > dis[i][k] + dis[k][j]:
                dis[i][j] = dis[i][k] + dis[k][j]


_min = float("inf")
it = itertools.permutations(r)
for iterR in it:
    _dis = 0
    start = iterR[0]
    for end in iterR[1:]:
        _dis += dis[start][end]
        start = end
    _min = min(_min, _dis)
print(_min)

"""
print("2 vs "+func(3, 3, [0, 1, 2], [[0, 1, 4], [1, 0, 1], [4, 1, 0]]))
print("4 vs "+func(3, 3, [0, 2], [[0, 2, 6], [2, 0, 2], [6, 2, 0]]))
print("3 vs "+func(4, 6, [1, 2, 3], [[0, 4, 6, 1], [4, 0, 3, 2], [6, 3, 0, 1], [1, 2, 1, 0]]))
# print("print(func({}, {}, {}, {}))".format(n, m, r, adj))
"""

Submission status: Time Limit Exceeded

Solution code:
import itertools

n, m, R = [int(i) for i in input().split()]
r = [int(i) - 1 for i in input().split()]
dis = [[float("inf") for _ in range(n)] for _ in range(n)]
for i in range(m):
    a, b, c = [int(i) for i in input().split()]
    dis[a - 1][b - 1] = c
    dis[b - 1][a - 1] = c

# 全ての頂点間の最短距離を算出、
for k in range(len(dis)):
    for i in range(len(dis)):
        for j in range(len(dis)):
            if dis[i][j] > dis[i][k] + dis[k][j]:
                dis[i][j] = dis[i][k] + dis[k][j]


_min = float("inf")
it = itertools.permutations(r)
for iterR in it:
    _dis = 0
    start = iterR[0]
    for end in iterR[1:]:
        _dis += dis[start][end]
        start = end
    _min = min(_min, _dis)
print(_min)

"""
print("2 vs "+func(3, 3, [0, 1, 2], [[0, 1, 4], [1, 0, 1], [4, 1, 0]]))
print("4 vs "+func(3, 3, [0, 2], [[0, 2, 6], [2, 0, 2], [6, 2, 0]]))
print("3 vs "+func(4, 6, [1, 2, 3], [[0, 4, 6, 1], [4, 0, 3, 2], [6, 3, 0, 1], [1, 2, 1, 0]]))
# print("print(func({}, {}, {}, {}))".format(n, m, r, adj))
"""

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations as perm
import sys


input = sys.stdin.readline


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

dest = (list)(map(lambda x: (int)(x)-1, input().split()))


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

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

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


ans = inf
for l in perm(dest):
    tmp = 0
    for i in range(R-1):
        tmp += mat[l[i]][l[i+1]]
    ans = min(ans, tmp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools

n, m, R = [int(i) for i in input().split()]
r = [int(i) - 1 for i in input().split()]
dis = [[float("inf") for _ in range(n)] for _ in range(n)]
for i in range(m):
    a, b, c = [int(i) for i in input().split()]
    dis[a - 1][b - 1] = c
    dis[b - 1][a - 1] = c

# 全ての頂点間の最短距離を算出、
for k in range(len(dis)):
    for i in range(len(dis)):
        for j in range(len(dis)):
            if dis[i][j] > dis[i][k] + dis[k][j]:
                dis[i][j] = dis[i][k] + dis[k][j]


_min = float("inf")
it = itertools.permutations(r)
for iterR in it:
    _dis = 0
    for j in range(1, len(iterR)):
        _dis += dis[iterR[j]][iterR[j-1]]
    _min = min(_min, _dis)
print(_min)

"""
print("2 vs "+func(3, 3, [0, 1, 2], [[0, 1, 4], [1, 0, 1], [4, 1, 0]]))
print("4 vs "+func(3, 3, [0, 2], [[0, 2, 6], [2, 0, 2], [6, 2, 0]]))
print("3 vs "+func(4, 6, [1, 2, 3], [[0, 4, 6, 1], [4, 0, 3, 2], [6, 3, 0, 1], [1, 2, 1, 0]]))
# print("print(func({}, {}, {}, {}))".format(n, m, r, adj))
"""

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations as perm
N, M, R = (list)(map(int, input().split()))

dest = (list)(map(lambda x: (int)(x)-1, input().split()))

inf = 10**10
mat = [[inf]*N for _ in range(N)]
for i in range(N):
    mat[i][i] == 0
for _ in range(M):
    a, b, c = (list)(map(int, input().split()))
    mat[a-1][b-1] = c
    mat[b-1][a-1] = c

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

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


ans = inf
for l in perm(dest):
    tmp = 0
    for i in range(R-1):
        tmp += mat[l[i]][l[i+1]]
    ans = min(ans, tmp)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools

inf = 10 ** 9
n, m, R = [int(i) for i in input().split()]
r = [int(i) - 1 for i in input().split()]
dis = [[inf for _ in range(n)] for _ in range(n)]
for i in range(m):
    a, b, c = [int(i) for i in input().split()]
    dis[a - 1][b - 1] = c
    dis[b - 1][a - 1] = c

# 全ての頂点間の最短距離を算出、
for k in range(len(dis)):
    for i in range(len(dis)):
        for j in range(len(dis)):
            if dis[i][j] > dis[i][k] + dis[k][j]:
                dis[i][j] = dis[i][k] + dis[k][j]


_min = inf
for iterR in itertools.permutations(r):
    _dis = 0
    for j in range(1, len(iterR)):
        _dis += dis[iterR[j]][iterR[j-1]]
    _min = min(_min, _dis)
print(_min)

"""
print("2 vs "+func(3, 3, [0, 1, 2], [[0, 1, 4], [1, 0, 1], [4, 1, 0]]))
print("4 vs "+func(3, 3, [0, 2], [[0, 2, 6], [2, 0, 2], [6, 2, 0]]))
print("3 vs "+func(4, 6, [1, 2, 3], [[0, 4, 6, 1], [4, 0, 3, 2], [6, 3, 0, 1], [1, 2, 1, 0]]))
# print("print(func({}, {}, {}, {}))".format(n, m, r, adj))
"""