Problem:


  MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Minimum Spanning Tree

  For a given weighted graph $G = (V, E)$, find the minimum spanning tree (MST) of $G$ and print total weight of edges belong to the MST.

Input

  In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, a $n \times n$ adjacency matrix $A$ which represents $G$ is given.
$a_{ij}$ denotes the weight of edge connecting vertex $i$ and vertex $j$. If there is no edge between $i$ and $j$, $a_{ij}$ is given by -1.

Output

Print the total weight of the minimum spanning tree of $G$.

Constraints

$1 \leq n \leq 100$

$0 \leq a_{ij} \leq 2,000$ (if $a_{ij} \neq -1$)

$a_{ij} = a_{ji}$

$G$ is a connected graph

Sample Input 1

5
 -1 2 3 1 -1
 2 -1 -1 4 -1
 3 -1 -1 1 1
 1 4 1 -1 3
 -1 -1 1 3 -1

Sample Output 1

5

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.



Sample input:
5
 -1 2 3 1 -1
 2 -1 -1 4 -1
 3 -1 -1 1 1
 1 4 1 -1 3
 -1 -1 1 3 -1


Sample output:
5

Submission status: Accepted

Solution code:
import heapq

def root(x):
    path_to_root = []
    while P[x] != x:
        path_to_root.append(x)
        x = P[x]
    for node in path_to_root:
        P[node] = x
    return x
def is_same_set(x,y):
    return root(x) == root(y)
def unite(x,y):
    P[root(x)] = root(y)

W = 0
N = int(input().strip())
P = [i for i in range(N)]
A = []
for i in range(N):
    v = list(map(int,input().strip().split(' ')))
    A.append(v)
edges = [] 
for i in range(N):
    for j in range(i,N):
        edge = [A[i][j],i,j]
        heapq.heappush(edges,edge)
while len(edges) > 0:
    e = heapq.heappop(edges)
    I = e[1]
    J = e[2]
    if e[0] != -1:
        if not is_same_set(I,J):
            unite(I,J)
            W += e[0]
print(W)

Submission status: Accepted

Solution code:
n = int(input())
T = [i for i in range(n)]
def root(x):
    path_to_root = []
    while T[x] != x:
        path_to_root.append(x)
        x = T[x]
    for node in path_to_root:
        T[node] = x
    return x
def is_same_set(x,y):
    return root(x) == root(y)
def unite(x,y):
    T[root(x)] = root(y)

A = []
W = []
for i in range(n):
    A.append(list(map(int,input().strip().split(' '))))
    for j in range(i+1,n):
        if A[i][j] != -1:
            W.append([A[i][j],i,j])
W.sort()
sum = 0
for i in range(len(W)):
    if not is_same_set(W[i][1],W[i][2]):
        unite(W[i][1],W[i][2])
        sum += W[i][0]
print(sum)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict

def push_vertex(vtx: int,queue: list, weights: dict, done: dict):
    queue.extend(weights[vtx])
    done[vtx] = True
    [queue.remove(x) for x in queue[:] if done[x[0]]]
    del weights[vtx]
    queue.sort(key=lambda x: x[1], reverse=True)
    return


def main():
    n = int(input())
    weights = defaultdict(list)
    for i in range(n):
        for idx, weight in enumerate(input().split()):
            if weight != '-1':
                weights[i+1].append((idx+1, int(weight)))
    done = {}
    for i in weights.keys():
        done[i] = False
    mst_weights = 0
    queue = []
    vtx = [*weights][0]
    push_vertex(vtx, queue, weights, done)

    while len(weights) != 0:
        new_vtx, new_vtx_weight = queue.pop()
        mst_weights += new_vtx_weight
        #print(f"connect to {new_vtx} ,weight={new_vtx_weight}")
        push_vertex(new_vtx, queue, weights, done)

    print(mst_weights)
    return

main()

Submission status: Accepted

Solution code:
from sys import maxsize
from functools import reduce

WHITE = 0
GRAY = 1
BLACK = 2


def read_adj_mat():
    n = int(input())
    M = []
    for _ in range(n):
        M.append([maxsize if x == "-1" else int(x)
                  for x
                  in input().split()])
    return n, M


def min_sp_tree(n, M):
    d = [maxsize] * n
    p = [-1] * n
    color = [WHITE] * n

    d[0] = 0

    while True:
        minv = maxsize
        u = -1

        for i in range(n):
            if minv > d[i] and color[i] != BLACK:
                u = i
                minv = d[i]

        if u == -1:
            break

        color[u] = BLACK
        for v in range(n):
            if color[v] != BLACK and M[u][v] != maxsize:
                if d[v] > M[u][v]:
                    d[v] = M[u][v]
                    p[v] = u
                    color[v] = GRAY

    return sum([M[i][p[i]] for i in range(n) if p[i] != -1])


def main():
    n, M = read_adj_mat()
    print(min_sp_tree(n, M))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
E = []
for _ in range(n):
    E.append(list(map(int, input().strip().split())))

class Node:
    def __init__(self, n):
        self.data = n
        self.parent = self
        self.rank = 0
    def find(self):
        if self.parent.data == self.data:
            return self
        else:
            ret = self.parent.find()
            self.parent = ret
            return ret
    def union(self, rhs):
        lhs = self
        lhs_root = lhs.find()
        rhs_root = rhs.find()
        if lhs_root.rank > rhs_root.rank:
            rhs_root.parent = lhs
        elif rhs_root.rank > lhs_root.rank:
            lhs_root.parent = rhs
        elif lhs_root.data != rhs_root.data:
            lhs_root.parent = rhs_root
            rhs_root.rank += 1
    def is_same(self, rhs):
        lhs = self
        return lhs.find().data == rhs.find().data

V = [Node(i) for i in range(n)]
inf = 2005

for i in range(n):
    for j in range(n):
        E[i][j] = [E[i][j], i, j, 0 if E[i][j] != -1 else inf]
min_op = lambda n: n[0] + n[3]

remain = n-1
sum_w = 0
while remain > 0:
    min_edge = min([min(E[i], key=min_op) for i in range(n)], key=min_op)
    w, i, j, _ = min_edge
    E[i][j][3] = E[j][i][3] = inf
    if not V[i].is_same(V[j]):
        V[i].union(V[j])
        sum_w += w
        remain -= 1
print(sum_w)

Submission status: Accepted

Solution code:
N = int(input())
G = [[] for i in range(N)]
for v in range(N):
    for w, c in enumerate(map(int, input().split())):
        if c != -1:
            G[v].append((w, c))

from heapq import heappush, heappop, heapify
used = [0]*N
que = [(c, w) for w, c in G[0]]
used[0] = 1
heapify(que)

ans = 0
while que:
    cv, v = heappop(que)
    if used[v]:
        continue
    used[v] = 1
    ans += cv
    for w, c in G[v]:
        if used[w]:
            continue
        heappush(que, (c, w))
print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 22 11:44:37 2018
ALDS1-12-A
@author: maezawa
"""
import heapq

n = int(input())
amat = [[] for _ in range(n)]
for i in range(n):
    amat[i] = list(map(int, input().split()))

adj = [[] for _ in range(n+1)]
for i in range(n):
    for j in range(i, n):
        if amat[i][j] == -1:
            continue
        adj[i+1].append([amat[i][j], j+1])
        adj[j+1].append([amat[j][i], i+1])

#print(adj)
d = [10**10]*(n+1)
h = []
heapq.heappush(h, [0, 1]) # [cost, node]
visited = [False]*(n+1)
while h:
    cost, node = heapq.heappop(h)
    if visited[node] == False and cost < d[node]:
        d[node] = cost
        visited[node] = True
        for nextnode in adj[node]:
            if visited[nextnode[1]]:
                continue
            heapq.heappush(h,nextnode)

d.pop(0)
print(sum(d))

Submission status: Accepted

Solution code:
INFTY = 1 << 21
WHITE = 0
GRAY = 1
BLACK = 2

def prim(n, m):
    d = [INFTY] * n
    p = [-1] * n
    color = [WHITE] * n

    d[0] = 0

    while True:
        minv = INFTY
        u = -1
        for i in range(n):
            if minv > d[i] and color[i] != BLACK:
                u = i
                minv = d[i]
        if u == -1:
            break
        color[u] = BLACK
        for v in range(n):
            if color[v] != BLACK and m[u][v] != INFTY:
                if d[v] > m[u][v]:
                    d[v] = m[u][v]
                    p[v] = u
                    color[v] = GRAY

    w_sum = 0
    for i in range(n):
        if p[i] != -1:
            w_sum += m[i][p[i]]

    return w_sum


n = int(input())
m = []
for i in range(n):
    line = [int(v) for v in input().split()]
    for j in range(n):
        if line[j] == -1:
            line[j] = INFTY
    m.append(line)

print(prim(n, m))

Submission status: Accepted

Solution code:
n = int(input())
a = []
b = []
c = []

def root(x):
    global rs
    if rs[x] == x:
        return(x)
    else:
        return(root(rs[x]))

for _ in range(n):
    a.append(list(map(int,input().split())))
for i in range(n):
    for j in range(i+1,n):
        if a[i][j] >= 0:
            b.append([a[i][j],i,j])
rs = [(i) for i in range(n)]

b.sort()
ans = 0
while(len(b)):
    if root(b[0][1]) != root(b[0][2]):
        ans += b[0][0]
        rs[root(rs[b[0][2]])] = root(b[0][1])
        c.append(b[0])
    del(b[0])
print(ans)

Submission status: Accepted

Solution code:
infinity = float('inf')
n = int(input())
a = []

for i in range(n):

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

    for i in range(len(line)):
        if line[i] == -1:
            line[i] = infinity
    a.append(line)

checked = [False] * n
d = [infinity] * n
checked[0] = True
ansswer = 0
next = 0

for i in range(n - 1):
    for j in range(n):
        if a[next][j] < d[j]:
            d[j] = a[next][j]

    minimumNeightbor = 0
    minimumWeight = infinity

    for j in range(n):
        if not checked[j] and d[j] < minimumWeight:
            minimumNeightbor = j
            minimumWeight = d[j]

    checked[minimumNeightbor] = True
    next = minimumNeightbor
    ansswer += minimumWeight

print(ansswer)

Submission status: Accepted

Solution code:
n = int(input())
a = [list(map(int, input().split())) for i in range(n)]
m = [2001] * n
f = [0] * n
sum = 0

m[0] = 0
f[0] = 1
v = 0

for i in range(n-1) :
    for j in range(n) :
        if (a[v][j] < m[j]) & (f[j] == 0) & (a[v][j] != -1):
            m[j] = a[v][j]
    
    min = 2001
    minj = 0
    for j in range(n) :
        if (m[j] < min) & (f[j] == 0):
            min = m[j]
            minj = j
    
    v = minj
    f[minj] = 1
    sum += min

print(sum)

Submission status: Accepted

Solution code:
# coding: utf-8
import heapq
n=int(input())
cost=[]
used=[False for i in range(n)]
for i in range(n):
    cost.append(list(map(int,input().split())))
q=[]
heapq.heappush(q,(0,0))
ans=0
while len(q):
    c,newv=heapq.heappop(q)
    if used[newv]:
        continue
    used[newv]=True
    ans+=c
    for nxt in range(n):
        if cost[newv][nxt]!=-1 and not used[nxt]:
            heapq.heappush(q,(cost[newv][nxt],nxt))
print(ans)

Submission status: Accepted

Solution code:
# Graph II - Minimum Spanning Tree
def mst(length, adj_m):
    """ Prims's Algorithm """
    cost = 0
    X,Y = [0], [i+1 for i in range(length-1)]
    while len(Y):
        min_cost = 2001
        ey = -1
        for x in X:
            for y in Y:
                t = adj_m[x][y]
                if not t == -1:
                    if min_cost > t:
                        min_cost = t
                        ey = y
        X.append(ey)
        Y.remove(ey)
        cost += min_cost
    return cost

n = int(input())
adj_m = [[-1 for _ in range(n)] for _ in range(n)]
for j in range(n):
    for i,v in enumerate(input().split()):
        adj_m[j][i] = int(v)
min_weight = mst(n, adj_m)
print(min_weight)

Submission status: Runtime Error

Solution code:
import heapq

n = int(input())
#A = [[int(i) for i in input().split()] for i in range(n)]
h = []
DP = {}
heapq.heappush(h,(0,0))
c = 0
while(len(DP)<n):
    tmp = heapq.heappop(h)
    if tmp[1] in DP:
        continue
    c += tmp[0]
    DP[tmp[1]] = 1
    for i,j in enumerate(A[tmp[1]]):
        if j > 0 and not i in DP:
            heapq.heappush(h,(j,i))
print(c)

Submission status: Runtime Error

Solution code:
graph_n=int(input())


edge_dict={}



for i in range(graph_n):
    tmp_row=list(map(int,input()))
    for j in range(graph_n):
        if(tmp_row[j]!=-1):
            try:
                edge_dict[tmp_row].append([i,j])
            except:
                edge_dict[tmp_row]=[[i,j]]

sorted_edge=sorted(edge_dict.items())
vertex_flag=[0]*graph_n

searched_vertex_num=0
cost=0

for edges in sorted_edge:
    for edge in edges[1]:
        if(vertex_flag[edge[0]]==0 and vertex_flag[edge[1]]==0):
            vertex_flag[edge[0]]=1
            vertex_flag[edge[1]]=1
            seached_vertex_num+=2
            cost+=edges[0]
            if(graph_n <=searched_vertex_num):
                break

        elif(vertex_flag[edge[0]]==0 and vertex_flag[edge[1]]==1):
            vertex_flag[edge[0]]=1
            vertex_flag[edge[1]]=1
            seached_vertex_num+=1
            cost+=edges[0]
            if(graph_n <=searched_vertex_num):
                break

        elif(vertex_flag[edge[0]]==1 and vertex_flag[edge[1]]==0):
            vertex_flag[edge[0]]=1
            vertex_flag[edge[1]]=1
            seached_vertex_num+=1
            cost+=edges[0]
            if(graph_n <=searched_vertex_num):
                break

    if(graph_n <=searched_vertex_num):
        break


print(cost)

Submission status: Runtime Error

Solution code:
class UnionFind:
    def __init__(self, size):
        self.rank = [0] * size
        self.par = range(size)
        self.g_num = size

    def find(self, x):
        if x == self.par[x]: return x
        self.par[x] = self.find(self.par[x])
        return self.par[x]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def unite(self, x, y):
        x, y = self.find(x), self.find(y)
        if x == y: return

        self.g_num -= 1
        if (self.rank[x] > self.rank[y]):
            self.par[y] = x
        else:
            self.par[x] = y
            if (self.rank[x] == self.rank[y]): self.rank[y] += 1

    def group_num(self):
        return self.g_num



V, E = map(int, raw_input().split())
es = [map(int, raw_input().split()) for i in xrange(E)]
es.sort(key = lambda x: x[2])

uf = UnionFind(V)
ans = 0
for e in es:
    if not uf.same(e[0], e[1]):
        uf.unite(e[0], e[1])
        ans += e[2]
print ans

Submission status: Runtime Error

Solution code:
def prim(cost):
    sumcost = 0
    V = len(cost)
    mincost = [float('inf')] * V
    used = [False] * V
    mincost[0] = 0
    while True:
        j = -1
        for i in range(V):
            if not used[i] and (j = -1 or mincost[i] < mincost[j]):
                j = i
        if j == -1:
            break
        used[j] = True
        sumcost = sumcost + mincost[j]
        for i in range(V):
            if cost[i][j] == -1:
                continue
            mincost[i] = min(mincost[i], cost[j][i])
    return sumcost

n = int(raw_input())
A = [0] * n
for i in range(n)
    A[i] = map(int, raw_input().split())

result = prim(A)
print(result)

Submission status: Runtime Error

Solution code:
n = int(raw_input())
A = [0]
i = 0
NY = range(1, n)
a = [[0 for i in xrange(n)] for j in xrange(n)
While i < n;
    a[i] = map(int,raw_input().split())
long = 0
while NY != []:
    amin = 2001
    for i in A:
        for j in NY:
            if 0 <= a[i][j] < amin:
                amin = a[i][j]
                addA = j
    A.append(addA)
    NY.remove(addA)
    long += amin
print long

Submission status: Runtime Error

Solution code:
n = int(raw_input())
A = [0]
i = 0
long = 0
NY = range(1, n)
a = [[0 for i in xrange(n)] for j in xrange(n)]
while i <= n:
    a[i] = map(int,raw_input().split())
    i = i+1
while NY != []:
    amin = 2001
    for i in A:
        for j in NY:
            if 0 <= a[i][j] < amin:
                amin = a[i][j]
                addA = j
    A.append(addA)
    NY.remove(addA)
    long =long + amin
print long

Submission status: Runtime Error

Solution code:
n = input()

INFTY = 10000000

color = [0 for i in range(n)]
M = [[0 for i in range(n)] for i in range(n)]
d = [INFTY for i in range(n)]
p = [-1 for i in range(n)]

def MST():
  d[0] = 0
  p[0] = -1

  while True:
    cost = INFTY
    for i in range(n):
      if color[i] != 1 and d[i] < cost:
        cost = d[i]
        u = i

    if cost == INFTY:
      break
    color[u] = 2

    for v in range(n):
      if color[v] != 2 and M[u][v] != INFTY:
      if M[u][v] < d[v]:
        d[v] = M[u][v]
        p[v] = u
        color[v] = 1:

  sum = 0
  for i in range(n):
    if p[i] != -1:
      sum += M[i][p[i]] 
  return sum

for i in range(n):
  G = map(int, raw_input().split())
  for j in range(n):
   if G[j] == -1:
     M[i][j] = INFTY
   else:
     M[i][j] = G[n]:

print MST()

Submission status: Runtime Error

Solution code:
n = input()

INFTY = 10000000

color = [0 for i in range(n)]
M = [[0 for i in range(n)] for i in range(n)]
d = [10000000 for i in range(n)]
p = [-1 for i in range(n)]

def MST():
  d[0] = 0
  p[0] = -1

  while True:
    cost = INFTY
    for i in range(n):
      if color[i] != 1 and d[i] < cost:
        cost = d[i]
        u = i

    if cost == INFTY:
      break
    color[u] = 2

    for v in range(n):
      if color[v] != 2 and M[u][v] != INFTY:
      if M[u][v] < d[v]:
        d[v] = M[u][v]
        p[v] = u
        color[v] = 1:

  sum = 0
  for i in range(n):
    if p[i] != -1:
      sum += M[i][p[i]] 
  return sum

for i in range(n):
  G = map(int, raw_input().split())
  for j in range(n):
   if G[j] == -1:
     M[i][j] = INFTY
   else:
     M[i][j] = G[n]:

print MST()

Submission status: Runtime Error

Solution code:
n = input()

INFTY = 10000000

color = [0 for i in xrange(n)]
M = [[0 for i in xrange(n)] for i in xrange(n)]
d = [INFTY for i in xrange(n)]
p = [-1 for i in xrange(n)]

def MST():
  d[0] = 0
  p[0] = -1

  while True:
    cost = INFTY
    for i in xrange(n):
      if color[i] != 1 and d[i] < cost:
        cost = d[i]
        u = i

    if cost == INFTY:
      break
    color[u] = 2

    for v in xrange(n):
      if color[v] != 2 and M[u][v] != INFTY:
      if M[u][v] < d[v]:
        d[v] = M[u][v]
        p[v] = u
        color[v] = 1:

  sum = 0
  for i in xrange(n):
    if p[i] != -1:
      sum += M[i][p[i]] 
  return sum

for i in xrange(n):
  G = map(int, raw_input().split())
  for j in range(n):
   if G[j] == -1:
     M[i][j] = INFTY
   else:
     M[i][j] = G[n]:

print sum

Submission status: Runtime Error

Solution code:
n = input()

INFTY = 10000000

color = [0 for i in xrange(n)]
M = [[0 for i in xrange(n)] for i in xrange(n)]
d = [INFTY for i in xrange(n)]
p = [-1 for i in xrange(n)]

def MST():
  d[0] = 0
  p[0] = -1

  while True:
    cost = INFTY
    for i in xrange(n):
      if color[i] != 1 and d[i] < cost
        cost = d[i]
        u = i

    if cost == INFTY:
      break
    color[u] = 2

    for v in xrange(n):
      if color[v] != 2 and M[u][v] != INFTY:
      if M[u][v] < d[v]:
        d[v] = M[u][v]
        p[v] = u
        color[v] = 1:

  sum = 0
  for i in xrange(n):
    if p[i] != -1:
      sum += M[i][p[i]] 
  return sum

for i in xrange(n):
  G = map(int, raw_input().split())
  for j in range(n):
   if G[j] == -1:
     M[i][j] = INFTY
   else:
     M[i][j] = G[n]:

print MST()

Submission status: Runtime Error

Solution code:
n = input()

INFTY = 10000000

color = [0 for i in xrange(n)]
M = [[0 for i in xrange(n)] for i in xrange(n)]
d = [INFTY for i in xrange(n)]
p = [-1 for i in xrange(n)]

def MST():
  d[0] = 0
  p[0] = -1

  while True:
    cost = INFTY
    for i in xrange(n):
      if color[i] != 1 and d[i] < cost:
        cost = d[i]
        u = i

    if cost == INFTY:
      break
    color[u] = 2

    for v in xrange(n):
      if color[v] != 2 and M[u][v] != INFTY:
      if M[u][v] < d[v]:
        d[v] = M[u][v]
        p[v] = u
        color[v] = 1:

  sum = 0
  for i in xrange(n):
    if p[i] != -1:
      sum += M[i][p[i]] 
  return sum

for i in xrange(n):
  G = map(int, raw_input().split())
  for j in range(n):
   if G[j] == -1:
     M[i][j] = INFTY
   else:
     M[i][j] = G[n]

print MST()

Submission status: Runtime Error

Solution code:
n = input()

INFTY = 10000000

color = [0 for i in xrange(n)]
M = [[0 for i in xrange(n)] for i in xrange(n)]
d = [INFTY for i in xrange(n)]
p = [-1 for i in xrange(n)]

def MST():
  d[0] = 0

  while True:
    cost = INFTY
    for i in xrange(n):
      if color[i] != 1 and d[i] < cost:
        cost = d[i]
        u = i

    if cost == INFTY:
      break
    color[u] = 2

    for v in xrange(n):
      if color[v] != 2 and M[u][v] != INFTY:
        if M[u][v] < d[v]:
          d[v] = M[u][v]
          p[v] = u
          color[v] = 1:

  sum = 0
  for i in xrange(n):
    if p[i] != -1:
      sum += M[i][p[i]] 
  return sum

for i in xrange(n):
  G = map(int, raw_input().split())
  for j in range(n):
   if G[j] == -1:
     M[i][j] = INFTY
   else:
     M[i][j] = G[n]

print MST()

Submission status: Runtime Error

Solution code:
n = input()

INFTY = 10000000

color = [0 for i in xrange(n)]
M = [[0 for i in xrange(n)] for i in xrange(n)]
d = [INFTY for i in xrange(n)]
p = [-1 for i in xrange(n)]

def MST():
  d[0] = 0

  while True:
    cost = INFTY
    for i in xrange(n):
      if color[i] != 1 and d[i] < cost:
        cost = d[i]
        u = i

    if cost == INFTY:
      break
    color[u] = 2

    for v in xrange(n):
      if color[v] != 2 and M[u][v] != INFTY:
        if M[u][v] < d[v]:
          d[v] = M[u][v]
          p[v] = u
          color[v] = 1

  sum = 0
  for i in xrange(n):
    if p[i] != -1:
      sum += M[i][p[i]] 
  return sum

for i in xrange(n):
  G = map(int, raw_input().split())
  for j in range(n):
   if G[j] == -1:
     M[i][j] = INFTY
   else:
     M[i][j] = G[n]

print MST()

Submission status: Runtime Error

Solution code:
n = int( raw_input() )
A = [0]
p = range(1, n)
a = [ [ 0 for i in xrange(n) ] for j in xrange(n) ]
for i in xrange(n):
    a[i] = map( int,raw_input().split() )
l = 0
while p != []:
    a_min = 2001
    for i in A:
        for j in p:
            if 0 <= a[i][j] < a_min:
                a_min = a[i][j]
                add_A = j
    A.append( add_A )
    NY.remove( add_A )
    l += a_min
print l

Submission status: Runtime Error

Solution code:
from __future__ import division, print_function
from sys import stdin, maxint
 
 
def main():
    n = int(stdin.readline())
 
    M = []
    for _ in xrange(n):
        M.append([int(s) for s in stdin.readline().split()])
 
    g = set(xrange(1, num+1))
    index = g.pop()
    h = {index}
    weight = 0
 
    while g:
        minimum = maxint
        for j in h:
            mj = M[j-1]
            for i in g:
                if 0 <= mj[i-1] < minimum:
                    index = i
                    minimum = mj[i-1]
        h.add(index)
        g.remove(index)
        weight += minimum
 
  
 
 
main()

Submission status: Runtime Error

Solution code:
from __future__ import division, print_function
from sys import stdin, maxint
 
 
def main():
    num = int(stdin.readline())
 
    y = []
    for _ in xrange(num):
        it = iter(int(s) for s in stdin.readline().split()[1:])
        y.append([(next(it), next(it)) for _ in xrange(next(it))])
    weight = [maxint] * num
    weight[0] = 0
    t = set(xrange(1, num))
    index = 0
 
    while t:
        for v, cost in y[index]:
            if v not in t:
                continue
            weight[v] = min(weight[v], cost + weight[index])
        index = min(t, key=lambda i: weight[i])
        t.remove(index)
    for i, d in enumerate(weight):
        print(i, d)
 
 
main()

Submission status: Runtime Error

Solution code:
from __future__ import division, print_function
from sys import stdin, maxint
 
 
def main():
    num = int(stdin.readline())
 
    y = []
    for _ in xrange(num):
        it = iter(int(s) for s in stdin.readline().split()[1:])
        y.append([(next(it), next(it)) for _ in xrange(next(it))])
    weight = [maxint] * num
    weight[0] = 0
    t = set(xrange(1, num))
    index = 0
 
    while t:
        for v, cost in y[index]:
            if v not in t:
                continue
            weight[v] = min(weight[v], cost + weight[index])

        index = min(t, key=lambda i: weight[i])
        t.remove(index)

    for i, d in enumerate(weight):
        print(i, d)
 
 
main()

Submission status: Runtime Error

Solution code:
from __future__ import division, print_function
from sys import stdin, maxint
 
 
def main():
    num = int(stdin.readline())
 
    y = []
    for _ in xrange(num):
        it = iter(int(s) for s in stdin.readline().split()[1:])
        y.append([(next(it), next(it)) for _ in xrange(next(it))])
    weight = [maxint] * num
    weight[0] = 0
    t = set(xrange(1, num))
    index = 0
 
    while t:
        for v, cost in y[index]:
            if v not in t:
                continue
            weight[v] = min(weight[v], cost + weight[index])

         index = min(t, key=lambda i: weight[i])
        t.remove(index)

    for i, d in enumerate(weight):
        print(i, d)
 
 
main()

Submission status: Runtime Error

Solution code:
from __future__ import division, print_function
from sys import stdin, maxint
 
 
def main():
    num = int(stdin.readline())
 
    y = []
    for _ in xrange(num):
        it = iter(int(s) for s in stdin.readline().split()[1:])
        y.append([(next(it), next(it)) for _ in xrange(next(it))])
 
    weight = [maxint] * num
    weight[0] = 0
    t = set(xrange(1, num))
    index = 0
 
    while t:
        for v, cost in y[index]:
            if v not in t:
                continue
            weight[v] = min(weight[v], cost + weight[index])

        index = min(t, key=lambda i: weight[i])
        t.remove(index)
 
    for i, d in enumerate(weight):
        print(i, d)
 
 
main()

Submission status: Runtime Error

Solution code:
from __future__ import division, print_function
from sys import stdin, maxint
 
 
def main():
    num = int(stdin.readline())
 
    y = []
    for _ in xrange(num):
        it = iter(int(s) for s in stdin.readline().split()[1:])
        y.append([(next(it), next(it)) for _ in xrange(next(it))])
 
    weight = [maxint] * num
    weight[0] = 0
    t = set(xrange(1, num))
    index = 0
 
    while t:
        for v, cost in y[index]:
            if v not in t:
                continue
            weight[v] = min(weight[v], cost + weight[index])
 
        index = min(t, key=lambda i: weight[i])
        t.remove(index)
 
    for i, d in enumerate(weight):
        print(i, d)
 
 
main()

Submission status: Runtime Error

Solution code:
n = int(raw_input())
a = [[0 for i in xrange(0,n)] for j in xrange(0,n)]
  
for i in xrange(n):
    a[i] = map(int,raw_input().split())
omomi = 0
A = [0]
B = range(1, n)
while B! = []:
    c=2000
    for i in A:
        for j in B:
            if 0 <= a[i][j]<=c:
                c = a[i][j]
                AA = j
    omomi = omomi + c
print omomi

Submission status: Runtime Error

Solution code:
n = int(raw_input())
a = [[0 for i in xrange(0,n)] for j in xrange(0,n)]
  
for i in xrange(n):
    a[i] = map(int,raw_input().split())
omomi = 0
A = [0]
B = range(1, n)
while B! = []:
    c=2000
    for i in A:
        for j in B:
            if 0 <= a[i][j]<=c:
                c = a[i][j]
    omomi = omomi + c
print omomi

Submission status: Runtime Error

Solution code:
def prim(n):
    d = [None] * 100
    p = [None] * 100
    color = [None] * 100
    
    for i in xrange(n):
        d[i] = float('inf')
        p[i] = -1
        color[i] = 0
    
    d[0] = 0
    
    while(true):
        minv = float('inf')
        u = -1
        for i in xrange(n):
            if minv > d[i] and color[i] != 2:
                u = i
                minv = d[i]
        
        if u == -1:
            break
        
        color[u] = 2
        
        for v in xrange(n):
            if color[v] != 2 and data[u][v] != float('inf'):
                if (d[v] > data[u][v]):
                    d[v] = data[u][v]
                    p[v] = u
                    color[v] = 1
    
    sum_val = 0
    for i in xrange(n):
        if p[i] != -1:
            sum_val += data[i][p[i]]
    
    return sum_val
    
n = input()
data = [None] * n
for i in xrange(n):
    data[i] = [None] * n
    line = map(int, raw_input().split())
    for j in xrange(n):
        if line[j] == -1:
            data[i][j] = float('inf')
        else:
            data[i][j] = line[j];
print prim(n)

Submission status: Runtime Error

Solution code:
n = input()
 
INFTY = float('inf')
 
color = [0 for i in range(n)]
m = [[INFTY for i in range(n)] for j in range(n)]
d = [INFTY for i in range(n)]
k = [-1 for i in range(n)]
 
d[0] = 0
 
while 1:
    cost = INFTY
for i in range(n):
    if color[i] != 2 and d[i] < cost:
        cost = d[i]
        u = i

if cost == INFTY:
    break
    
color[u] = 2
 
for v in range(n):
    if color[v] != 2 and m[u][v] != INFTY and m[u][v] < d[v]:
        d[v] = m[u][v]
        k[v] = u
        color[v] = 1
sum = 0
for i in range(n):
    if p[i] != -1:
        sum += m[i][k[i]]
return sum
 
for i in range(n):
    G = map(int, raw_input().split())
    for j in range(n):
    if G[j] != -1:
        m[i][j] = G[j]

Submission status: Runtime Error

Solution code:
n = input()
 
INFTY = float('inf')
 
color = [0 for i in range(n)]
m = [[INFTY for i in range(n)] for j in range(n)]
d = [INFTY for i in range(n)]
k = [-1 for i in range(n)]

for i in range(n):
    G = map(int, raw_input().split())
    for j in range(n):
    if G[j] != -1:
        m[i][j] = G[j]

d[0] = 0
 
while 1:
    cost = INFTY
for i in range(n):
    if color[i] != 2 and d[i] < cost:
        cost = d[i]
        u = i

if cost == INFTY:
    break
    
color[u] = 2
 
for v in range(n):
    if color[v] != 2 and m[u][v] != INFTY and m[u][v] < d[v]:
        d[v] = m[u][v]
        k[v] = u
        color[v] = 1
sum = 0
for i in range(n):
    if p[i] != -1:
        sum += m[i][k[i]]
print sum

Submission status: Runtime Error

Solution code:
n = input()
 
INFTY = float('inf')
 
color = [0 for i in range(n)]
m = [[INFTY for i in range(n)] for j in range(n)]
d = [INFTY for i in range(n)]
k = [-1 for i in range(n)]

for i in range(n):
    G = map(int, raw_input().split())
    for j in range(n):
        if G[j] != -1:
            m[i][j] = G[j]

d[0] = 0
 
while 1:
    cost = INFTY
for i in range(n):
    if color[i] != 2 and d[i] < cost:
        cost = d[i]
        u = i

if cost == INFTY:
    break
    
color[u] = 2
 
for v in range(n):
    if color[v] != 2 and m[u][v] != INFTY and m[u][v] < d[v]:
        d[v] = m[u][v]
        k[v] = u
        color[v] = 1
sum = 0
for i in range(n):
    if p[i] != -1:
        sum += m[i][k[i]]
print sum

Submission status: Runtime Error

Solution code:
n = int(raw_input())
 
INFTY = float('inf')
 
color = [0 for i in range(n)]
m = [[INFTY for i in range(n)] for j in range(n)]
d = [INFTY for i in range(n)]
k = [-1 for i in range(n)]

for i in range(n):
    G = map(int, raw_input().split())
    for j in range(n):
        if G[j] != -1:
            m[i][j] = G[j]

d[0] = 0
 
while 1:
    cost = INFTY
for i in range(n):
    if color[i] != 2 and d[i] < cost:
        cost = d[i]
        u = i

if cost == INFTY:
    break
    
color[u] = 2
 
for v in range(n):
    if color[v] != 2 and m[u][v] != INFTY and m[u][v] < d[v]:
        d[v] = m[u][v]
        k[v] = u
        color[v] = 1
sum = 0
for i in range(n):
    if p[i] != -1:
        sum += m[i][k[i]]
print sum