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

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


def dijkstra(s, n, w, cost):
    # 始点sから各頂点への最短距離
    # n:頂点数,　w:辺の数, cost[u][v] : 辺uvのコスト(存在しないときはinf)
    d = [float("inf")] * n
    used = [False] * n
    d[s] = 0

    while True:
        v = -1
        # まだ使われてない頂点の中から最小の距離のものを探す
        for i in range(n):
            if (not used[i]) and (v == -1):
                v = i
            elif (not used[i]) and d[i] < d[v]:
                v = i
        if v == -1:
            break
        used[v] = True

        for j in range(n):
            d[j] = min(d[j], d[v] + cost[v][j])
    return d


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

route_list=[[0]*N for i in range(N)]

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

#print(route_list)

wa_list=warshall_floyd(route_list)
r_list=[[0]*N for i in range(N)]
ans=10**9

for perm in permutations(r):
    cur = sum(wa_list[v][u] for v, u in zip(perm, perm[1:]))
    ans = min(ans, cur)


print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import itertools
input = sys.stdin.readline
inf = 200000000
n, m, r = map(int,input().split())
rs = list(map(int,input().split()))
d = [[inf] * (n+1) for j in range(n+1)]
for i in range(n+1):
    d[i][i] = 0
for i in range(m):
    a, b, c = map(int, input().split())
    d[a][b] = d[b][a] = c
for k in range(1,n+1):
    for i in range(1,n+1):
        for j in range(i+1,n+1):
            d[i][j] = d[j][i] = min(d[i][j], d[i][k] + d[k][j])
p = list(itertools.permutations(range(r)))
s = inf
for q in p:
    t = 0
    for i in range(r-1):
        t += d[rs[q[i]]][rs[q[i+1]]]
    if s > t:
        s = t
print(s)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

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

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

ans = 10**10
for course in list(itertools.permutations(Visit)):
    sum1 = 0
    for i in range(lVisit-1):
        to = course[i+1]
        fm = course[i]
        sum1 += Data[fm-1][to-1]
    ans = min(ans,sum1)
print(ans)

Submission status: Time Limit Exceeded

Solution code:



def wantans(nowp,sc,rlis,ans):

    if len(rlis) == 0:
        ans = min(ans , sc)
        return ans

    for i in range(len(rlis)):

        nexsc = sc
        nexlis = rlis.copy()
        del nexlis[i]

        if nowp != None:
            nexsc += lis[nowp][rlis[i]]
            
        ans = wantans(rlis[i],nexsc,nexlis,ans)

    return ans
        




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

r = list(map(int,input().split()))

lis = [ [float("inf")] * N for i in range(N) ]

for i in range(N):

    lis[i][i] = 0

for i in range(M):

    A,B,C = map(int,input().split())

    A -= 1
    B -= 1

    lis[A][B] = C
    lis[B][A] = C

for k in range(N):

    for i in range(N):

        for j in range(N):

            lis[i][j] = min(lis[i][j],lis[i][k]+lis[k][j])



for i in range(R):
    r[i] -= 1
    
ans = wantans(None,0,r,float("inf"))

print (ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
def main():

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

    dist = [[float('inf') for _ in range(N)] for _ in range(N)]
    for i in range(N): dist[i][i] = 0
    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(N):
        for i in range(N):
            for j in range(N):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

    path = itertools.permutations(r)
    ans = float('inf')
    for p in path:
        d = 0
        for i in range(len(p)-1):
            d += dist[p[i]][p[i+1]]
        ans = min(ans, d)

    return ans

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

Submission status: Time Limit Exceeded

Solution code:
import itertools

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

def main():
  n, m, r = map(int, input().split())
  list_r = list(map(int, input().split()))
  list_cand = list(itertools.permutations(list_r))

  dist = [[float("inf") if i != j else 0 for j in range(n)] for i in range(n)]
  for i in range(m):
    a, b, c = map(int, input().split())
    dist[a-1][b-1] = c
    dist[b-1][a-1] = c
  min_dist = warshall_floyd(dist)

  result = 10**100
  for one_cand in list_cand:
    temp = 0
    idx = 0
    while idx < r-1:
      temp += min_dist[one_cand[idx]-1][one_cand[idx+1]-1]
      idx += 1
    if temp < result:
      result = temp
  print(result)

if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
import itertools

n, m, r = map(int, input().split())
list_r = [one_r-1 for one_r in map(int, input().split())]

dist = [[float("inf")] * n for _ in range(n)]
for i in range(n):
  dist[i][i] = 0
for i in range(m):
  a, b, c = map(int, input().split())
  dist[a-1][b-1] = c
  dist[b-1][a-1] = c
for k in range(n):
  for i in range(n):
    for j in range(n):
      if dist[i][j] > dist[i][k] + dist[k][j]:
        dist[i][j] = dist[i][k] + dist[k][j]

result = float("inf")
for one_cand in itertools.permutations(list_r):
  temp = 0
  for i in range(r-1):
    temp += dist[one_cand[i]][one_cand[i+1]]
  if temp < result:
    result = temp
print(result)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
import sys

N, M, R = map(int, sys.stdin.readline().split())
r = [i - 1 for i in map(int, sys.stdin.readline().split())]
        
d = [[float('inf')] * N for _ in range(N)]
        
for i in range(N):
  d[i][i] = 0
            
for i in range(M):
  a, b, c = map(int,sys.stdin.readline().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):
        if d[i][j] > d[i][k] + d[k][j]:
          d[i][j] = d[i][k] + d[k][j]
        
ans = 10**12
        
for each in permutations(r):
  t_dis = 0
  for i in range(R-1):
    t_dis += d[each[i]][each[i+1]]  
            
  ans = min(ans, t_dis)
        
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
n, m, r = map(int, input().split())
list_r = [one_r-1 for one_r in map(int, input().split())]

dist = [[float("inf")] * n for _ in range(n)]
for i in range(n):
  dist[i][i] = 0
for i in range(m):
  a, b, c = map(int, input().split())
  dist[a-1][b-1] = c
  dist[b-1][a-1] = c
for k in range(n):
  for i in range(n):
    for j in range(n):
      if dist[i][j] > dist[i][k] + dist[k][j]:
        dist[i][j] = dist[i][k] + dist[k][j]

result = float("inf")
for one_cand in permutations(list_r):
  temp = 0
  for i in range(r-1):
    temp += dist[one_cand[i]][one_cand[i+1]]
  if temp < result:
    result = temp
print(result)

Submission status: Time Limit Exceeded

Solution code:
import itertools
n, m, r = map(int, input().split())
list_r = [one_r-1 for one_r in map(int, input().split())]

dist = [[float("inf")] * n for _ in range(n)]
for i in range(n):
  dist[i][i] = 0
for i in range(m):
  a, b, c = map(int, input().split())
  dist[a-1][b-1] = c
  dist[b-1][a-1] = c
for k in range(n):
  for i in range(n):
    for j in range(n):
      if dist[i][j] > dist[i][k] + dist[k][j]:
        dist[i][j] = dist[i][k] + dist[k][j]

result = float("inf")
for one_cand in itertools.permutations(list_r):
  temp = 0
  for i in range(r-1):
    temp += dist[one_cand[i]][one_cand[i+1]]
  if temp < result:
    result = temp
print(result)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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


n, m, r = map(int, input().split())
list_r = list(map(int, input().split()))
list_r = [one_r-1 for one_r in list_r]
dist = [[float("inf") for _ in range(n)] for _ in range(n)]
for i in range(n):
  dist[i][i] = 0
for i in range(m):
  a, b, c = map(int, input().split())
  dist[a-1][b-1] = c
  dist[b-1][a-1] = c
min_dist = warshall_floyd(dist)

result = float("inf")
for one_cand in itertools.permutations(list_r):
  temp = 0
  for i in range(r-1):
    temp += min_dist[one_cand[i]][one_cand[i+1]]
  if temp < result:
    result = temp
print(result)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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


n, m, r = map(int, input().split())
list_r = list(map(int, input().split()))
list_cand = itertools.permutations(list_r)
dist = [[float("inf") if i != j else 0 for j in range(n)] for i in range(n)]
for i in range(m):
  a, b, c = map(int, input().split())
  dist[a-1][b-1] = c
  dist[b-1][a-1] = c
min_dist = warshall_floyd(dist)

result = 10**100
for one_cand in list_cand:
  temp = 0
  for i in range(r-1):
    temp += min_dist[one_cand[i]-1][one_cand[i+1]-1]
  if temp < result:
    result = temp
print(result)

Submission status: Time Limit Exceeded

Solution code:
import itertools

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


n, m, r = map(int, input().split())
list_r = list(map(int, input().split()))
list_cand = list(itertools.permutations(list_r))

dist = [[float("inf") if i != j else 0 for j in range(n)] for i in range(n)]
for i in range(m):
  a, b, c = map(int, input().split())
  dist[a-1][b-1] = c
  dist[b-1][a-1] = c
min_dist = warshall_floyd(dist)

result = 10**100
for one_cand in list_cand:
  temp = 0
  idx = 0
  while idx < r-1:
    temp += min_dist[one_cand[idx]-1][one_cand[idx+1]-1]
    idx += 1
  if temp < result:
    result = temp
print(result)

Submission status: Time Limit Exceeded

Solution code:
from itertools import permutations
INF = 1 << 30
n, m, r = map(int, input().split())

d = [[INF for j in range(200)] for i in range(200)]
for i in range(200):
    d[i][i]=0

R = [int(_) for _ in input().split()]
for i in range(r):
    R[i] -= 1

for i in range(m):
    s,t,u = map(int,input().split())
    s -= 1
    t -= 1
    d[s][t] = u
    d[t][s] = u

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

res = INF
for tpl in list(permutations(range(r),r)):
    tmp = 0
    for i in range(r-1):
        tmp += d[R[tpl[i]]][R[tpl[i+1]]]
    res = min(res,tmp)

print(res)

Submission status: Time Limit Exceeded

Solution code:
import itertools


class Graph:
    def __init__(self, n_nodes):
        self.n_nodes = n_nodes
        self.edges = [[] for _ in range(n_nodes)]

    def add_edge(self, s, t, d=None, undirected=False):
        if d is not None:
            self.edges[s].append((t, d))
        else:
            self.edges[s].append(t)
        if undirected:
            self.add_edge(t, s, d)

    def add_edges(self, edges, undirected=False):
        for edge in edges:
            self.add_edge(*edge, undirected=undirected)


class FloydWarshall:
    def __init__(self, graph):
        self.graph = graph
        self.distances = [[float('inf')] * graph.n_nodes
                          for _ in range(graph.n_nodes)]
        self.nexts = [[None] * graph.n_nodes for _ in range(graph.n_nodes)]
        self._init()

    def _init(self):
        for x in range(self.graph.n_nodes):
            self.distances[x][x] = 0
        for source in range(self.graph.n_nodes):
            for destination, distance in self.graph.edges[source]:
                self.distances[source][destination] = distance
                self.nexts[source][destination] = destination

    def compute_shortest_path_lengths(self):
        for k in range(self.graph.n_nodes):
            for i in range(self.graph.n_nodes):
                for j in range(self.graph.n_nodes):
                    s = self.distances[i][k] + self.distances[k][j]
                    if s < self.distances[i][j]:
                        self.distances[i][j] = s
                        self.nexts[i][j] = self.nexts[i][k]

    def get_shortest_path(self, x, y):
        if self.nexts[x][y] is None:
            return []
        path = [x]
        while path[-1] != y:
            s = path[-1]
            t = self.nexts[s][y]
            path.append(t)
        return path


n, m, r = map(int, input().split())
rs = list(map(int, input().split()))

graph = Graph(n + 1)
graph.add_edges([list(map(int,
                          input().split())) for _ in range(m)],
                undirected=True)
fw = FloydWarshall(graph)
fw.compute_shortest_path_lengths()
res = float('inf')
for perm in itertools.permutations(rs):
    s = sum([fw.distances[a][b] for a, b in zip(perm, perm[1:])])
    res = min(res, s)
print(res)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500000)


def dfs(c,p,d):
    if c == R:
        if ans[0] > d:
            ans[0] = d
        return
    for i in range(R):
        if memo[i]:continue
        memo[i] = True
        if p == -1:
            dfs(c+1,i,0)
        else:dfs(c+1,i,d+graph[r[p]][r[i]])
        memo[i] = False

N,M,R = map(int,input().split())
r = [i-1 for i in map(int,input().split())]
graph = [[float("Inf") if i != j else 0 for i in range(N)] for j in range(N)]
for i in range(M):
    x,y,z = map(int,input().split())
    graph[x-1][y-1] = z
    graph[y-1][x-1] = z
for k in range(N):
    for i in range(N):
        for j in range(N):
            if graph[i][j] > graph[i][k] + graph[k][j]:
                graph[i][j] = graph[i][k] + graph[k][j]
memo = [False]*R
ans = [float("Inf")]
dfs(0,-1,0)
print(ans[0])

Submission status: Time Limit Exceeded

Solution code:
def dfs(c,p,d):
    if c == R:
        if ans[0] > d:
            ans[0] = d
    for i in range(R):
        if memo[i]:continue
        memo[i] = True
        if p == -1:
            dfs(c+1,i,0)
        else:dfs(c+1,i,d+graph[r[p]][r[i]])
        memo[i] = False

N,M,R = map(int,input().split())
r = [i-1 for i in map(int,input().split())]
graph = [[float("Inf") if i != j else 0 for i in range(N)] for j in range(N)]
for i in range(M):
    x,y,z = map(int,input().split())
    graph[x-1][y-1] = z
    graph[y-1][x-1] = z
for k in range(N):
    for i in range(N):
        for j in range(N):
            if graph[i][j] > graph[i][k] + graph[k][j]:
                graph[i][j] = graph[i][k] + graph[k][j]
memo = [False]*R
ans = [float("Inf")]
dfs(0,-1,0)
print(ans[0])

Submission status: Time Limit Exceeded

Solution code:
import itertools,heapq
INFTY = 10**8
N,M,R = map(int,input().split())
R = list(map(int,input().split()))
G = {}
for _ in range(M):
    A,B,C = map(int,input().split())
    if A not in G:
        G[A] = []
    G[A].append((B,C))
    if B not in G:
        G[B] = []
    G[B].append((A,C))
D = [[INFTY for j in range(N+1)] for i in range(N+1)]
for i in range(1,N+1):
    hist = [0 for _ in range(N+1)]
    heap = [(0,i)]
    while heap:
        cur = heapq.heappop(heap)
        if hist[cur[1]]==0:
            hist[cur[1]] = 1
            for x in G[cur[1]]:
                if hist[x[0]]==0:
                    if D[i][x[0]]>cur[0]+x[1]:
                        D[i][x[0]] = cur[0]+x[1]
                        heapq.heappush(heap,(D[i][x[0]],x[0]))
dmin = INFTY
for r in itertools.permutations(R,len(R)):
    d = 0
    for i in range(1,len(r)):
        d += D[r[i]][r[i-1]]
    dmin = min(dmin,d)
print(dmin)

Submission status: Time Limit Exceeded

Solution code:
import itertools,heapq
INFTY = 10**8
N,M,R = map(int,input().split())
R = list(map(int,input().split()))
G = {}
for _ in range(M):
    A,B,C = map(int,input().split())
    if A not in G:
        G[A] = []
    G[A].append((B,C))
    if B not in G:
        G[B] = []
    G[B].append((A,C))
D = [[INFTY for j in range(N+1)] for i in range(N+1)]
for i in range(1,N+1):
    hist = [0 for _ in range(N+1)]
    heap = [(0,i)]
    while heap:
        cur = heapq.heappop(heap)
        hist[cur[1]] = 1
        for x in G[cur[1]]:
            if hist[x[0]]==0:
                if D[i][x[0]]>cur[0]+x[1]:
                    D[i][x[0]] = cur[0]+x[1]
                    heapq.heappush(heap,(D[i][x[0]],x[0]))
dmin = INFTY
for r in itertools.permutations(R,len(R)):
    d = 0
    for i in range(1,len(r)):
        d += D[r[i]][r[i-1]]
    dmin = min(dmin,d)
print(dmin)

Submission status: Time Limit Exceeded

Solution code:
import math,itertools
INFTY = 10**8
N,M,R = map(int,input().split())
R = list(map(int,input().split()))
G = {}
for _ in range(M):
    A,B,C = map(int,input().split())
    if A not in G:
        G[A] = []
    G[A].append((B,C))
    if B not in G:
        G[B] = []
    G[B].append((A,C))
D = [[INFTY for j in range(N+1)] for i in range(N+1)]
for i in range(1,N+1):
    if i in G:
        for x in G[i]:
            D[i][x[0]] = x[1]
for k in range(1,N+1):
    for i in range(1,N+1):
        for j in range(1,N+1):
            D[i][j] = min(D[i][j],D[i][k]+D[k][j])
dmin = INFTY
for r in itertools.permutations(R,len(R)):
    d = 0
    for i in range(1,len(r)):
        d += D[r[i]][r[i-1]]
    dmin = min(dmin,d)
print(dmin)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(500000)

def dfs(v,d):
    memo[i][v] = d
    for k in graph[v]:
        if memo[i][k[0]] != -1:
            if memo[i][k[0]] > d+k[1]:
                dfs(k[0],d+k[1])
                continue
            continue
        dfs(k[0],d+k[1])

def check(count,last,distance):
    if (count == r):
        if (ans[0] > distance ):ans[0] = distance
        return
    for i in range(r):
        if seen[i]:continue
        seen[i] = True
        if last == -1:check(count+1,i,0)
        else:check(count+1,i,distance+memo[R[last]-1][R[i]-1])
        seen[i] = False

n,m,r = map(int,input().split())
R = list(map(int,input().split()))
graph = [[] for _ in range(n)]
for i in range(m):
    x,y,z = map(int,input().split())
    graph[x-1].append([y-1,z])
    graph[y-1].append([x-1,z])
memo = [[-1]*n for _ in range(n)]
for i in range(n):
    dfs(i,0)
seen = [False]*r
ans = [float("Inf")]
check(0,-1,0)
print(*ans)

Submission status: Time Limit Exceeded

Solution code:
def dfs(count,last,distance):
    if (count == r):
        if (ans[0] > distance ):ans[0] = distance
        return
    for i in range(r):
        if seen[i]:continue
        seen[i] = True
        if last == -1:dfs(count+1,i,0)
        else:dfs(count+1,i,distance+dp[R[last]-1][R[i]-1])
        seen[i] = False

n,m,r = map(int,input().split())
R = list(map(int,input().split()))
dp = [[ 0 if i == j else float("inf") for i in range(n)] for j in range(n)]
for i in range(m):
    x,y,z = map(int,input().split())
    dp[x-1][y-1] = z
    dp[y-1][x-1] = z
for k in range(n):
    for i in range(n):
        for j in range(n):
            if dp[i][j] > dp[i][k] + dp[k][j]:
                dp[i][j] = dp[i][k] + dp[k][j]
ans = [float("Inf")]
seen = [False]*r
dfs(0,-1,0)
print(*ans)

Submission status: Time Limit Exceeded

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

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

way_cost = [[float('inf')]*N for _ in range(N)]

for idx in range(N):
    way_cost[idx][idx] = 0

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

# ワーシャルフロイド法で全ての街同士の最短距離を求める
shortest_path_cost = copy.deepcopy(way_cost)
for between_point in range(N):
    for start_point in range(N):
        for end_point in range(N):
            shortest_path_cost[start_point][end_point] \
                = min(shortest_path_cost[start_point][end_point],
                      shortest_path_cost[start_point][between_point]+shortest_path_cost[between_point][end_point])

# 巡回ルートを総当りで調べ、最小コストを出力する
route_list = list(itertools.permutations(r))

ans = float('inf')
for route in route_list:
    cost = 0
    for idx in range(R-1):
        cost += shortest_path_cost[route[idx]][route[idx+1]]
    ans = min(ans,cost)

print(int(ans))

Submission status: Time Limit Exceeded

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

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

way_cost = [[float('inf')]*N for _ in range(N)]

for idx in range(N):
    way_cost[idx][idx] = 0

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

# ワーシャルフロイド法で全ての街同士の最短距離を求める
shortest_path_cost = floyd_warshall(csgraph=way_cost, directed=False)

# 巡回ルートを総当りで調べ、最小コストを出力する
route_list = list(itertools.permutations(r))

for route in route_list:
    route_list.remove(route[::-1])

ans = float('inf')
for route in route_list:
    cost = 0
    for idx in range(R-1):
        cost += shortest_path_cost[route[idx]][route[idx+1]]
    ans = min(ans,cost)

print(int(ans))

Submission status: Time Limit Exceeded

Solution code:
import copy, itertools

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

way_cost = [[float('inf')]*N for _ in range(N)]

for idx in range(N):
    way_cost[idx][idx] = 0

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

# ワーシャルフロイド法で全ての街同士の最短距離を求める
shortest_path_cost = copy.deepcopy(way_cost)
for between_point in range(N):
    for start_point in range(N):
        for end_point in range(N):
            shortest_path_cost[start_point][end_point] \
            = min(shortest_path_cost[start_point][end_point], \
            shortest_path_cost[start_point][between_point]+shortest_path_cost[between_point][end_point])

# 巡回ルートを総当りで調べ、最小コストを出力する
route_list = list(itertools.permutations(r))

for route in route_list:
    route_list.remove(route[::-1])

ans = float('inf')
for route in route_list:
    cost = 0
    for idx in range(R-1):
        cost += shortest_path_cost[route[idx]][route[idx+1]]
        if cost >= ans:
            break
    ans = min(ans,cost)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import copy, itertools

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

way_cost = [[float('inf')]*N for _ in range(N)]

for idx in range(N):
    way_cost[idx][idx] = 0

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

# ワーシャルフロイド法で全ての街同士の最短距離を求める
shortest_path_cost = copy.deepcopy(way_cost)
for between_point in range(N):
    for start_point in range(N):
        for end_point in range(N):
            shortest_path_cost[start_point][end_point] \
            = min(shortest_path_cost[start_point][end_point], \
            shortest_path_cost[start_point][between_point]+shortest_path_cost[between_point][end_point])

# 巡回ルートを総当りで調べ、最小コストを出力する
route_list = list(itertools.permutations(r))

for route in route_list:
    route_list.remove(route[::-1])

ans = float('inf')
for route in route_list:
    cost = 0
    for idx in range(R-1):
        cost += shortest_path_cost[route[idx]][route[idx+1]]
    ans = min(ans,cost)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import copy, itertools

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

way_cost = [[float('inf')]*N for _ in range(N)]

for idx in range(N):
    way_cost[idx][idx] = 0

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

# ワーシャルフロイド法で全ての街同士の最短距離を求める
shortest_path_cost = copy.deepcopy(way_cost)
for between_point in range(N):
    for start_point in range(N):
        for end_point in range(N):
            shortest_path_cost[start_point][end_point] \
            = min(shortest_path_cost[start_point][end_point], \
            shortest_path_cost[start_point][between_point]+shortest_path_cost[between_point][end_point])

# 巡回ルートを総当りで調べ、最小コストを出力する
route_list = list(itertools.permutations(r))
ans = float('inf')
for route in route_list:
    cost = 0
    for idx in range(R-1):
        cost += shortest_path_cost[route[idx]][route[idx+1]]
    ans = min(ans,cost)

print(ans)

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(1,N+1):
        for i in range(1,N+1):
            for j in range(1,N+1):
                d[i][j] = min(d[i][j], d[i][k]+d[k][j])


    ans = INF
    
    for i in permutations(r):
        ta = 0
        for x in range(R-1):
            ta += d[i[x]][i[x+1]]
        
        if(ta < ans):
            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
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(1,N+1):
        for i in range(1,N+1):
            for j in range(1,N+1):
                d[i][j] = min(d[i][j], d[i][k]+d[k][j])


    ans = INF
    
    for i in permutations(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
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(1,N+1):
        for i in range(1,N+1):
            for j in range(1,N+1):
                d[i][j] = min(d[i][j], d[i][k]+d[k][j])


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