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

Solution code:
class Node:
    def __init__(self):
        pass

class Edge:
    def __init__(self,edge,cost=1):
        self.node_from=edge[0]
        self.node_to=edge[1]
        self.cost=cost

    def add_node(self,node):
        self.nodes.append(node)

class myGraph:

    def __init__(self):
        self.adj={}
        self.nodes={}

    def add_edge(self,edge,cost):
        if len(edge)==1:
            edge=list(edge)

        u,v=edge[0],edge[1]

        if u not in self.nodes:
            self.adj[u] = {}
            self.nodes[u] = {}

        if v not in self.nodes:
            self.adj[v] = {}
            self.nodes[v] = {}

        # add the edge
        self.adj[u][v] = cost
        self.adj[v][u] = cost

    def add_directed_edge(self,edge,cost):
        if len(edge)==1:
            edge=list(edge)


        u,v=edge[0],edge[1]

        if u not in self.nodes:
            self.adj[u] = {}
            self.nodes[u] = {}

        if v not in self.nodes:
            self.adj[v] = {}
            self.nodes[v] = {}

        self.adj[u][v] = cost

    def get_edges_from(self,node):
        return [(self.adj[node][nn],node,nn) for nn in self.adj[node]]


    def makeEdgeobj(self):
        edges=[]
        for sn in self.nodes:
            for e in self.get_edges_from(sn):
                edges.append(Edge([e[1],e[2]],e[0]))

        return edges

    def _add(self,edges,add_edges):
        for e in add_edges:
            hq.heappush(edges,e)
        return edges

    def bermn_ford(self,start,init=0):

        nodes=self.nodes
        dists={}
        for n in nodes:
            dists[n]=float("inf")

        dists[start]=init
        edges=self.makeEdgeobj()

        for i in range(len(nodes)):
            update=False
            for k in range(len(edges)):
                e=edges[k]
                if  dists[e.node_from]!=float("inf") and dists[e.node_to]>dists[e.node_from]+e.cost:
                    dists[e.node_to]=dists[e.node_from]+e.cost
                    update=True

            if i==len(nodes)-1:
                return False

            if not update:
                break

        return dists


    def dijkstra(self,start, goal=None):
        import heapq
        '''
            get minimum cost
        '''

        N = len(self.adj)          # グラフのノード数
        #dist = [float('inf') for i in range(N)] # 始点から各頂点までの最短距離を格納する
        dist = {k:float('inf') for k in self.nodes}
        #prev = [float('inf') for i in range(N)]

        dist[start] = 0
        visited = []

        koho=[]
        heapq.heappush(koho,(0,start))

        vtx=list(self.nodes)
        vtx.remove(start)

        while len(koho)!=0:
            d,mini=heapq.heappop(koho)
            if dist[mini]<d:
                continue


            for k in list(self.adj[mini]):
                cost=self.adj[mini][k]
                if cost != float('inf') and dist[k]>dist[mini]+cost:# and not(k in visited):
                    dist[k]=dist[mini]+cost
                    heapq.heappush(koho,(dist[k],k))
                    #prev[k]=mini

        return dist

    def prim(self):

        import heapq

        nodes=list(self.nodes.keys())
        N=len(nodes)

        X=[nodes[0]]
        unused=[]
        for u in self.adj[X[0]]:
            heapq.heappush(unused,(self.adj[X[0]][u],X[0],u))

        total_cost=0
        used={n:False for n in nodes}
        used[X[0]]=True
        while True:
            #print(unused)
            #print(X,total_cost)
            cost,u,v=heapq.heappop(unused)
            if used[v]:
                continue
            X.append(v)
            used[v]=True
            total_cost+=cost
            if len(X)==N:
                break

            for u in self.adj[v]:
                if used[u]:
                    continue
                heapq.heappush(unused,(self.adj[u][v],v,u))

        return total_cost




    def show(self):

        import networkx as nx
        import matplotlib.pyplot as plt
        G=nx.Graph()

        for u in self.adj:
            for v in self.adj[u]:

                #G.add_edge(e.node_from,e.node_to,weight=e.cost)
                G.add_edge(u,v,weight=self.adj[u][v])
                #print(e.node_from,e.node_to,e.cost)

        pos=nx.spring_layout(G)
        #nx.draw_networkx_edges(G,pos=pos,edgelist=G.edges())
        edge_weight=dict([((u,v,),int(d['weight'])) for u,v,d in G.edges(data=True)])

        nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_weight)
        #nx.draw_networkx_labels(G, pos)
        nx.draw_networkx_nodes(G,pos)
        nx.draw_networkx_edges(G,pos)
        nx.draw_networkx_labels(G,pos)
        #plt.axis('off')
        #nx.draw(G,with_labels=True)
        plt.show()



def spaceinput():
    s=input()
    return list(map(int,s.split(" ")))

if __name__=="__main__":
    N,M,R=spaceinput()
    r=spaceinput()

    g=myGraph()


    for i in range(M):
        ss=spaceinput()
        g.add_edge((ss[0],ss[1]),ss[2])

    r=list(set(r))

    g2=myGraph()
    for sr in r:
        ds=g.dijkstra(sr)
        for d in ds:
            if d==sr:
                continue
            if d in r:
                g2.add_edge((sr,d),ds[d])



    minl=10*20
    adj=g2.adj
    #print(adj)

    def search(u,visited,l):
        global minl

        #print(visited)
        if l>minl:
            return


        if sum(visited.values())==len(r):
            minl=l
            return

        for v in adj[u]:
            #print(u,v)
            if v==u:
                continue
            if not visited[v]:
                l+=adj[u][v]
                visited[v]=True
                search(v,visited,l)
                l-=adj[u][v]
                visited[v]=False


    l=0
    visited={}
    for u in r:
        visited[u]=False
    for v in r:
        visited[v]=True
        search(v,visited,l)
        visited[v]=False


    '''


    import itertools as it
    #print(g.adj)
    #print(g2.adj)


    for pm in it.permutations(r):
        l=0
        #print(pm)
        for i in range(1,len(pm)):
            l+=g2.adj[pm[i-1]][pm[i]]


        if l<minl:
            minl=l
    '''

    print(minl)

Submission status: Wrong Answer

Solution code:
import itertools
def dist(a, b, l):
# 	return (l[a][b]+l[b][a])
	
	if l[a][b] == 0: return (l[b][a])
	if l[b][a] == 0: return (l[a][b])
	
	if l[a][b] > l[b][a]:
		return (l[b][a])
	else:
		return (l[a][b])


N, M, R = map(int, input().split())		# 5 7 2
r = [int(i) for i in input().split()]	# 1 2 3 4 5 ...

r = list(set(r))

ans = 100000 * 200 * 200

c = [[ans for i in range(N+1)] for j in range(N+1)]

for i in range(1, M+1):
	A, B, C = map(int, input().split())		# 5 7 2
	c[A][B]=C


# print(c)
# print(dist(A, B, c))

ans = 100000 * 200 * 200

# for i in range(len(r)-1):
# # 	print(r[i])
# 	ans += dist(r[i], r[i+1], c)

# print(ans)

for l in list(itertools.permutations(r)):
	sum = 0
	for i in range(len(l)-1):
		sum += dist(l[i], l[i+1], c)
	
	ans = min(ans, sum)
# 	print(l, sum, ans)


print(ans)

Submission status: Wrong Answer

Solution code:
def i1():
 return int(input())
def i2():
 return [int(i) for i in input().split()]
[N,M,R]=i2()
r=i2()
f=2**20
d=[[f for j in range(N)]for i in range(N)]
for i in range(N):d[i][i]=0
for i in range(M):
    a=i2()
    d[a[0]-1][a[1]-1]=a[2]
    d[a[1]-1][a[0]-1]=a[2]
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])

c=2**20

import itertools
for i in list(itertools.permutations(r)):
    ddd=0
    for j in range(len(i)-1):
       ddd+=d[i[j]-1][i[j+1]-1]
    c=min(c,ddd)
print(c)

Submission status: Wrong Answer

Solution code:
from itertools import permutations

N, M, R = map(int, raw_input().split())
g = [[0 for x in xrange(N)] for x in xrange(N)]
r = map(int, raw_input().split())
r = [x-1 for x in r]
for m in xrange(0, M):
    A, B, C = map(int, raw_input().split())
    A -= 1
    B -= 1
    g[B][A] = C
    g[A][B] = C
# print g

for k in xrange(N):
    for i in xrange(N):
        for j in xrange(i+1, N):
            g[j][i] = g[i][j] = min(g[j][i], g[i][k]+g[k][j])
# print g

min_d = 10000000000
n = len(r)
for rr in permutations(r):
    # print rr
    d = 0
    for i in xrange(n-1):
        d += g[rr[i]][rr[i+1]]
    min_d = min(d, min_d)
print min_d

Submission status: Wrong Answer

Solution code:

from heapq import *

def search(s, length, N, M, R):

    d = [100000+1]*N
    d[s-1] = 0

    prev = [None]*N

    pq = [(100000+1, i+1) for i in range(N)]
    heapify(pq)
    heapreplace(pq, (0, s))

    while len(pq) > 0:
        u = heappop(pq)
        for v, c in length.get(u[1], []):
            alt = d[u[1]-1] + c
            if d[v-1] > alt:
                d[v-1] = alt
                prev[v-1] = u
                heappush(pq, (alt, v))
    return d

def main():
    length = {}

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

    r = [int(a) for a in input().split()]

    for _ in range(M):
        a, b, c = list(map(int, input().split(' ')))
        length[a] = length.get(a, []) + [(b, c)]
        length[b] = length.get(b, []) + [(a, c)]

    res = 0
    for i in range(R):
        if i+1 < R:
            d = search(r[i], length, N, M, R)
            res += d[r[i+1]-1]

    print(res)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
class Node:
    def __init__(self):
        pass

class Edge:
    def __init__(self,edge,cost=1):
        self.node_from=edge[0]
        self.node_to=edge[1]
        self.cost=cost

    def add_node(self,node):
        self.nodes.append(node)

class myGraph:

    def __init__(self):
        self.adj={}
        self.nodes={}

    def add_edge(self,edge,cost):
        if len(edge)==1:
            edge=list(edge)

        u,v=edge[0],edge[1]

        if u not in self.nodes:
            self.adj[u] = {}
            self.nodes[u] = {}

        if v not in self.nodes:
            self.adj[v] = {}
            self.nodes[v] = {}

        # add the edge
        self.adj[u][v] = cost
        self.adj[v][u] = cost

    def add_directed_edge(self,edge,cost):
        if len(edge)==1:
            edge=list(edge)


        u,v=edge[0],edge[1]

        if u not in self.nodes:
            self.adj[u] = {}
            self.nodes[u] = {}

        if v not in self.nodes:
            self.adj[v] = {}
            self.nodes[v] = {}

        self.adj[u][v] = cost

    def get_edges_from(self,node):
        return [(self.adj[node][nn],node,nn) for nn in self.adj[node]]


    def makeEdgeobj(self):
        edges=[]
        for sn in self.nodes:
            for e in self.get_edges_from(sn):
                edges.append(Edge([e[1],e[2]],e[0]))

        return edges

    def _add(self,edges,add_edges):
        for e in add_edges:
            hq.heappush(edges,e)
        return edges

    def bermn_ford(self,start,init=0):

        nodes=self.nodes
        dists={}
        for n in nodes:
            dists[n]=float("inf")

        dists[start]=init
        edges=self.makeEdgeobj()

        for i in range(len(nodes)):
            update=False
            for k in range(len(edges)):
                e=edges[k]
                if  dists[e.node_from]!=float("inf") and dists[e.node_to]>dists[e.node_from]+e.cost:
                    dists[e.node_to]=dists[e.node_from]+e.cost
                    update=True

            if i==len(nodes)-1:
                return False

            if not update:
                break

        return dists


    def dijkstra(self,start, goal=None):
        import heapq
        '''
            get minimum cost
        '''

        N = len(self.adj)          # グラフのノード数
        #dist = [float('inf') for i in range(N)] # 始点から各頂点までの最短距離を格納する
        dist = {k:float('inf') for k in self.nodes}
        #prev = [float('inf') for i in range(N)]

        dist[start] = 0
        visited = []

        koho=[]
        heapq.heappush(koho,(0,start))

        vtx=list(self.nodes)
        vtx.remove(start)

        while len(koho)!=0:
            d,mini=heapq.heappop(koho)
            if dist[mini]<d:
                continue


            for k in list(self.adj[mini]):
                cost=self.adj[mini][k]
                if cost != float('inf') and dist[k]>dist[mini]+cost:# and not(k in visited):
                    dist[k]=dist[mini]+cost
                    heapq.heappush(koho,(dist[k],k))
                    #prev[k]=mini

        return dist

    def prim(self):

        import heapq

        nodes=list(self.nodes.keys())
        N=len(nodes)

        X=[nodes[0]]
        unused=[]
        for u in self.adj[X[0]]:
            heapq.heappush(unused,(self.adj[X[0]][u],X[0],u))

        total_cost=0
        used={n:False for n in nodes}
        used[X[0]]=True
        while True:
            #print(unused)
            #print(X,total_cost)
            cost,u,v=heapq.heappop(unused)
            if used[v]:
                continue
            X.append(v)
            used[v]=True
            total_cost+=cost
            if len(X)==N:
                break

            for u in self.adj[v]:
                if used[u]:
                    continue
                heapq.heappush(unused,(self.adj[u][v],v,u))

        return total_cost




    def show(self):

        import networkx as nx
        import matplotlib.pyplot as plt
        G=nx.Graph()

        for u in self.adj:
            for v in self.adj[u]:

                #G.add_edge(e.node_from,e.node_to,weight=e.cost)
                G.add_edge(u,v,weight=self.adj[u][v])
                #print(e.node_from,e.node_to,e.cost)

        pos=nx.spring_layout(G)
        #nx.draw_networkx_edges(G,pos=pos,edgelist=G.edges())
        edge_weight=dict([((u,v,),int(d['weight'])) for u,v,d in G.edges(data=True)])

        nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_weight)
        #nx.draw_networkx_labels(G, pos)
        nx.draw_networkx_nodes(G,pos)
        nx.draw_networkx_edges(G,pos)
        nx.draw_networkx_labels(G,pos)
        #plt.axis('off')
        #nx.draw(G,with_labels=True)
        plt.show()



def spaceinput():
    s=input()
    if len(s)==0:
        return False
    return list(map(int,s.split(" ")))

if __name__=="__main__":
    N,M,R=spaceinput()
    r=spaceinput()

    g=myGraph()


    for i in range(M):
        ss=spaceinput()
        g.add_edge((ss[0],ss[1]),ss[2])

    r=list(set(r))

    g2=myGraph()
    for sr in r:
        ds=g.dijkstra(sr)
        for d in ds:
            if d in r:
                g2.add_edge((sr,d),ds[d])



    minl=10*30
    adj=g2.adj
    #print(adj)

    def search(u,visited,l):
        global minl

        #print(visited)
        if l>minl:
            return


        if sum(visited.values())==len(r):
            minl=l
            return

        for v in adj[u]:
            #print(u,v)
            if v==u:
                continue
            if not visited[v]:
                l+=adj[u][v]
                visited[v]=True
                search(v,visited,l)
                l-=adj[u][v]
                visited[v]=False


    l=0
    visited={}
    for u in r:
        visited[u]=False
    for v in r:
        visited[v]=True
        search(v,visited,l)
        visited[v]=False


    '''


    import itertools as it
    #print(g.adj)
    #print(g2.adj)


    for pm in it.permutations(r):
        l=0
        #print(pm)
        for i in range(1,len(pm)):
            l+=g2.adj[pm[i-1]][pm[i]]


        if l<minl:
            minl=l
    '''

    print(minl)

Submission status: Wrong Answer

Solution code:
import itertools
def dist(a, b, l):
# 	return (l[a][b]+l[b][a])
	
	if l[a][b] == 0: return (l[b][a])
	if l[b][a] == 0: return (l[a][b])
	
	if l[a][b] > l[b][a]:
		return (l[b][a])
	else:
		return (l[a][b])


N, M, R = map(int, input().split())		# 5 7 2
r = [int(i) for i in input().split()]	# 1 2 3 4 5 ...

r = list(set(r))

c = [[0 for i in range(N+1)] for j in range(N+1)]

for i in range(1, M+1):
	A, B, C = map(int, input().split())		# 5 7 2
	c[A][B]=C


# print(c)
# print(dist(A, B, c))

ans = 100000 * 200 * 200

# for i in range(len(r)-1):
# # 	print(r[i])
# 	ans += dist(r[i], r[i+1], c)

# print(ans)

for l in list(itertools.permutations(r)):
	sum = 0
	for i in range(len(l)-1):
		sum += dist(l[i], l[i+1], c)
	
	if ans==0: ans = sum
	ans = min(ans, sum)
# 	print(l, sum, ans)


print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python

import itertools
import sys

def main(argv):
    line = sys.stdin.readline()
    while line:
        N, M, R = map(lambda x: int(x), line.split(" ", 3))
        r  = map(lambda x: int(x) - 1, sys.stdin.readline().split(" "))
        weights = [[0 for i in xrange(N)] for j in xrange(N)]
        for i in xrange(M):
            a, b, c = map(lambda x: int(x), sys.stdin.readline().split(" ", 3))
            weights[a - 1][b - 1] = c
            weights[b - 1][a - 1] = c

        for k in xrange(N):
            for i in xrange(N):
                for j in xrange(N):
                    if j > i:
                        if weights[i][k] > 0 and weights[k][j] > 0:
                            length = weights[i][k] + weights[k][j]
                            if weights[i][j] == 0 or weights[i][j] > length:
                                weights[i][j] = length
                                weights[j][i] = length

        min_length = -1
#        for p in itertools.permutations(r):
#            length = 0
#            previous = p[0]
#            for i in p[1:]:
#                length += weights[previous][i]
#                previous = i
#            if min_length == -1:
#                min_length = length
#            elif min_length > length:
#                min_length = length
        print min_length

        line = sys.stdin.readline()

if __name__ == "__main__":
    main(sys.argv)

Submission status: Wrong Answer

Solution code:
class Node:
    def __init__(self):
        pass

class Edge:
    def __init__(self,edge,cost=1):
        self.node_from=edge[0]
        self.node_to=edge[1]
        self.cost=cost

    def add_node(self,node):
        self.nodes.append(node)

class myGraph:

    def __init__(self):
        self.adj={}
        self.nodes={}

    def add_edge(self,edge,cost):
        if len(edge)==1:
            edge=list(edge)

        u,v=edge[0],edge[1]

        if u not in self.nodes:
            self.adj[u] = {}
            self.nodes[u] = {}

        if v not in self.nodes:
            self.adj[v] = {}
            self.nodes[v] = {}

        # add the edge
        self.adj[u][v] = cost
        self.adj[v][u] = cost

    def add_directed_edge(self,edge,cost):
        if len(edge)==1:
            edge=list(edge)


        u,v=edge[0],edge[1]

        if u not in self.nodes:
            self.adj[u] = {}
            self.nodes[u] = {}

        if v not in self.nodes:
            self.adj[v] = {}
            self.nodes[v] = {}

        self.adj[u][v] = cost

    def get_edges_from(self,node):
        return [(self.adj[node][nn],node,nn) for nn in self.adj[node]]


    def makeEdgeobj(self):
        edges=[]
        for sn in self.nodes:
            for e in self.get_edges_from(sn):
                edges.append(Edge([e[1],e[2]],e[0]))

        return edges

    def _add(self,edges,add_edges):
        for e in add_edges:
            hq.heappush(edges,e)
        return edges

    def bermn_ford(self,start,init=0):

        nodes=self.nodes
        dists={}
        for n in nodes:
            dists[n]=float("inf")

        dists[start]=init
        edges=self.makeEdgeobj()

        for i in range(len(nodes)):
            update=False
            for k in range(len(edges)):
                e=edges[k]
                if  dists[e.node_from]!=float("inf") and dists[e.node_to]>dists[e.node_from]+e.cost:
                    dists[e.node_to]=dists[e.node_from]+e.cost
                    update=True

            if i==len(nodes)-1:
                return False

            if not update:
                break

        return dists


    def dijkstra(self,start, goal=None):
        import heapq
        '''
            get minimum cost
        '''

        N = len(self.adj)          # グラフのノード数
        #dist = [float('inf') for i in range(N)] # 始点から各頂点までの最短距離を格納する
        dist = {k:float('inf') for k in self.nodes}
        #prev = [float('inf') for i in range(N)]

        dist[start] = 0
        visited = []

        koho=[]
        heapq.heappush(koho,(0,start))

        vtx=list(self.nodes)
        vtx.remove(start)

        while len(koho)!=0:
            d,mini=heapq.heappop(koho)
            if dist[mini]<d:
                continue


            for k in list(self.adj[mini]):
                cost=self.adj[mini][k]
                if cost != float('inf') and dist[k]>dist[mini]+cost:# and not(k in visited):
                    dist[k]=dist[mini]+cost
                    heapq.heappush(koho,(dist[k],k))
                    #prev[k]=mini

        return dist

    def prim(self):

        import heapq

        nodes=list(self.nodes.keys())
        N=len(nodes)

        X=[nodes[0]]
        unused=[]
        for u in self.adj[X[0]]:
            heapq.heappush(unused,(self.adj[X[0]][u],X[0],u))

        total_cost=0
        used={n:False for n in nodes}
        used[X[0]]=True
        while True:
            #print(unused)
            #print(X,total_cost)
            cost,u,v=heapq.heappop(unused)
            if used[v]:
                continue
            X.append(v)
            used[v]=True
            total_cost+=cost
            if len(X)==N:
                break

            for u in self.adj[v]:
                if used[u]:
                    continue
                heapq.heappush(unused,(self.adj[u][v],v,u))

        return total_cost




    def show(self):

        import networkx as nx
        import matplotlib.pyplot as plt
        G=nx.Graph()

        for u in self.adj:
            for v in self.adj[u]:

                #G.add_edge(e.node_from,e.node_to,weight=e.cost)
                G.add_edge(u,v,weight=self.adj[u][v])
                #print(e.node_from,e.node_to,e.cost)

        pos=nx.spring_layout(G)
        #nx.draw_networkx_edges(G,pos=pos,edgelist=G.edges())
        edge_weight=dict([((u,v,),int(d['weight'])) for u,v,d in G.edges(data=True)])

        nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_weight)
        #nx.draw_networkx_labels(G, pos)
        nx.draw_networkx_nodes(G,pos)
        nx.draw_networkx_edges(G,pos)
        nx.draw_networkx_labels(G,pos)
        #plt.axis('off')
        #nx.draw(G,with_labels=True)
        plt.show()



def spaceinput():
    s=input()
    if len(s)==0:
        return False

    return list(map(int,s.split(" ")))

if __name__=="__main__":
    N,M,R=spaceinput()
    r=spaceinput()

    g=myGraph()


    for i in range(M):
        ss=spaceinput()
        g.add_edge((ss[0],ss[1]),ss[2])

    r=list(set(r))

    g2=myGraph()
    for sr in r:
        ds=g.dijkstra(sr)
        for d in ds:
            if d in r:
                g2.add_edge((sr,d),ds[d])



    minl=10*30
    adj=g2.adj
    #print(adj)
    '''
    def search(u,visited,l):
        global minl
        if l>minl:
            return

        if sum(visited.values())==len(r):
            minl=l
            return



        for v in adj:
            if not(v in visited):
                l+=adj[u][v]
                visited[v]=True
                search(v,visited,l)
                l-=adj[u][v]
                visited[v]=False


    l=0
    visited={}
    for u in r:
        visited[u]=False
    for v in r:
        visited[v]=True
        search(v,visited,l)
        visited[v]=False




    '''


    import itertools as it
    #print(g.adj)
    #print(g2.adj)


    for pm in it.permutations(r):
        l=0
        #print(pm)
        for i in range(1,len(pm)):
            l+=g2.adj[pm[i-1]][pm[i]]


        if l<minl:
            minl=l


    print(minl)

Submission status: Wrong Answer

Solution code:
import itertools
def dist(a, b, l):
# 	return (l[a][b]+l[b][a])
	
	if l[a][b] == 0: return (l[b][a])
	if l[b][a] == 0: return (l[a][b])
	
	if l[a][b] > l[b][a]:
		return (l[b][a])
	else:
		return (l[a][b])


N, M, R = map(int, input().split())		# 5 7 2
r = [int(i) for i in input().split()]	# 1 2 3 4 5 ...

c = [[0 for i in range(N+1)] for j in range(N+1)]

for i in range(1, M+1):
	A, B, C = map(int, input().split())		# 5 7 2
	c[A][B]=C


# print(c)
# print(dist(A, B, c))

ans = 100000 * 200 * 200

# for i in range(len(r)-1):
# # 	print(r[i])
# 	ans += dist(r[i], r[i+1], c)

# print(ans)

for l in list(itertools.permutations(r)):
	sum = 0
	for i in range(len(l)-1):
		sum += dist(l[i], l[i+1], c)
	
	if ans==0: ans = sum
	ans = min(ans, sum)
# 	print(l, sum, ans)


print(ans)

Submission status: Wrong Answer

Solution code:
from itertools import permutations
N, M, R = map(int, input().split())
r = [int(i) - 1 for i in input().split()]
d = [[10000000 for i in range(N)] for j in range(N)]
for i in range(M):
    A, B, C = map(int, input().split())
    d[A-1][B-1] = min(d[A-1][B-1], C)
    d[B-1][A-1] = min(d[A-1][B-1], C)
l = True
for o in permutations(r):
    tmp_l = 0
    for s, e in zip(o[:-1], o[1:]):
        tmp_l = tmp_l + d[s][e]
    if l is True:
        l = tmp_l
    else:
        l = min(l, tmp_l)
print(l)

Submission status: Wrong Answer

Solution code:
n,m,R=[int(x) for x in input().split()]
r=[int(x) -1 for x in input().split()]
d=[[float("inf") for _ in [0]*n] for _ in [0]*n]
for i in range(n):
    d[i][i]=0
for i in [0]*m:
    a,b,c=[int(x) for x in input().split()]
    d[a-1][b-1]=d[b-1][a-1]=c
from itertools import product,permutations
for i,j,k in product(range(n),range(n),range(n)):
    if k in r:
        continue
    if d[i][j] >d[i][k]+d[k][j]:
        d[i][j]=d[i][k]+d[k][j]
def Long(args):
    ans=0
    for i in range(len(args)-1):
        ans+=d[args[i+1]][args[i]]
    return ans
print(min(Long(i) for i in permutations(r)))

Submission status: Wrong Answer

Solution code:
import sys
from heapq import *
from itertools import *
MAX = 100000
input = sys.stdin.readline
N,M,R = map(int,input().split())
rlist = list(map(int,input().split()))
D = []
V = []
for i in range(N):
  D.append([MAX]*N)
  V.append([0]*N)
for i in range(N):
  D[i][i] = 0
H = []
heapify(H)
for _ in range(M):
  a,b,c = map(int,input().split())
  D[a-1][b-1] = c
  D[b-1][a-1] = c
  heappush(H,(a-1,b-1))
while H:
  a,b = heappop(H)
  if V[a][b] == 1:
    continue
  V[a][b] = 1
  V[b][a] = 1
  for i in range(N):
    if i not in {a,b}:
      d = D[i][a]+D[a][b]
      if D[i][b] > d:
        D[i][b] = d
        D[b][i] = d
        heappush(H,(i,b))
      d = D[a][b]+D[b][i]
      if D[a][i] > d:
        D[i][a] = d
        D[a][i] = d
        heappush(H,(i,a))
ret = N*100000
for l in permutations(rlist):
  d = 0
  for i in range(R-1):
    a = l[i]-1
    b = l[i+1]-1
    di = D[a][b]
    if di == -1:
      d = -1
      break
    d += di
  if d >= 0 and ret >= d:
    ret = d
print(ret)

Submission status: Wrong Answer

Solution code:
import itertools
def dist(a, b, l):
# 	return (l[a][b]+l[b][a])
	
	if l[a][b] == 0: return (l[b][a])
	if l[b][a] == 0: return (l[a][b])
	
	if l[a][b] > l[b][a]:
		return (l[b][a])
	else:
		return (l[a][b])


N, M, R = map(int, input().split())		# 5 7 2
r = [int(i) for i in input().split()]	# 1 2 3 4 5 ...

c = [[0 for i in range(N+1)] for j in range(N+1)]

for i in range(1, M+1):
	A, B, C = map(int, input().split())		# 5 7 2
	c[A][B]=C


# print(c)
# print(dist(A, B, c))

ans=0

# for i in range(len(r)-1):
# # 	print(r[i])
# 	ans += dist(r[i], r[i+1], c)

# print(ans)

sum=0
sum = 100000 * 200 * 200
for l in list(itertools.permutations(r)):
# 	print(l)
	sum=0
	for i in range(len(l)-1):
		sum += dist(l[i], l[i+1], c)
	
	if ans==0: ans = sum
	ans = min(ans, sum)


print(ans)

Submission status: Wrong Answer

Solution code:
import itertools
def dist(a, b, l):
# 	return (l[a][b]+l[b][a])
	
	if l[a][b] == 0: return (l[b][a])
	if l[b][a] == 0: return (l[a][b])
	
	if l[a][b] > l[b][a]:
		return (l[b][a])
	else:
		return (l[a][b])


N, M, R = map(int, input().split())		# 5 7 2
r = [int(i) for i in input().split()]	# 1 2 3 4 5 ...

c = [[0 for i in range(N+1)] for j in range(N+1)]

for i in range(1, M+1):
	A, B, C = map(int, input().split())		# 5 7 2
	c[A][B]=C


# print(c)
# print(dist(A, B, c))

ans=0

# for i in range(len(r)-1):
# # 	print(r[i])
# 	ans += dist(r[i], r[i+1], c)

# print(ans)

sum=0
for l in list(itertools.permutations(r)):
# 	print(l)
	sum=0
	for i in range(len(l)-1):
		sum += dist(l[i], l[i+1], c)
	
	if ans==0: ans = sum
	ans = min(ans, sum)


print(ans)

Submission status: Wrong Answer

Solution code:
import copy
tmp=input().split()
N=int(tmp[0])
M=int(tmp[1])
R=int(tmp[2])

r=[int(i) for i in input().split()]
ABC=[[int(j) for j in input().split()] for i in range(M)]

root=[[] for i in range(N+1)]
for i in range(M):
	root[ABC[i][0]].append([ABC[i][1],ABC[i][2]])
	root[ABC[i][1]].append([ABC[i][0],ABC[i][2]])
	
#構成
#[次の場所、距離]

#最短距離

#初期位置
ans=999999
def roop(here,left,length):
	#print(here)
	if len(left)==0:
		global ans		
		ans=min(ans,length)
		#print(str(here)+" "+str(ans))
	else:
		for next_ in left:
			tmpLeft=copy.deepcopy(left)
			tmpLeft.remove(next_)
			roop(next_,tmpLeft,length+minRootAll[here][next_])

			
	
def checkMinRoot(here):
	minRoot=[999999 for i in range(N+1)]
	minRoot[here]=0
	next=[here]
	while len(next)!=0:
		#ある地点からスタート
		now=next[-1]
		next.pop(-1)
		
		#ある地点までが現状最短経路なら、nextに加える
		for will in root[now]:
			if minRoot[will[0]] > minRoot[now]+will[1]:
				minRoot[will[0]] = minRoot[now]+will[1]
				next.append(will[0])
	return minRoot

#下準備		
minRootAll=[]
for i in range(N+1):
	minRootAll.append(checkMinRoot(i))

#計算
for i in r:
	tmpr=copy.deepcopy(r)
	#print("why!?")
	tmpr.remove(i)
	roop(i,tmpr,0)
print(ans)