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

Solution code:
import sys
INF = float('inf')
n = int(input())
adja_matrix = [[int(i) for i in line.split()] for line in sys.stdin.read().splitlines()]
condition = ['INIT'] * n
distance = [INF] * n
p = [0] * n
distance[0] = 0
p[0] = -1

while True:
    mincost = INF
    for i in range(n):
        if condition[i] != 'FINISH' and distance[i] < mincost:
            mincost = distance[i]
            u = i

    if mincost == INF:
        break

    condition[u] = 'FINISH'

    for v in range(n):
        if condition[i] != 'FINISH' and adja_matrix[u][v] != -1:
            if adja_matrix[u][v] < distance[v]:
                distance[v] = adja_matrix[u][v]
                p[v] = u
                condition[v] = 'CHECK'

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

print(sum)

Submission status: Wrong Answer

Solution code:
n = int(input())
m = []

for _ in range(n):
    tmp = [int(x) for x in input().split()]
    m.append(tmp)

edge_list = [] 

j = 1
for i in range(n-1):
    for k,x in enumerate(m[i][j:]):
        if x != -1:
            edge_list.append((x,i,k))
        else:
            pass
    j += 1
edge_list.sort()

root_list = [i for i in range(n)]

def root(x):
    path_to_root = []
    while root_list[x] != x:
        path_to_root.append(x)
        x = root_list[x]
    for node in path_to_root:
        root_list[node] = x
    return x

def is_same_root(x,y):
    return root(x) == root(y)

def unite(x,y):
    root_list[root(x)] = root(y)

cost = 0
for x in edge_list:
    w,p,q = x
    if is_same_root(p,q):
        pass
    else:
        cost += w
        unite(p,q)

print(cost)

Submission status: Wrong Answer

Solution code:

Submission status: Wrong Answer

Solution code:
import sys
    
global status, d
status = {}
d=0

def mst(p1, GRAPH):
    global status
    
    edge={}
    total = 0    
    while True:
        status[p1]=True
        for p2 in range(len(status)):
            if status[p2]==False and GRAPH.has_key((p1,p2)):
                edge[(p1, p2)]=GRAPH[(p1, p2)]
        mini = 2000
        for key, value in edge.items():
            if status[key[1]]==True:
                del edge[key]
                continue
            if value <mini:
                key0 = key
                mini = value
        if mini!=2000:
            total+=mini
            p1=key0[1]
        else:
            break
    
    return total

n = int(raw_input())
x = {}
for i in range(n):
    seq = map(int,raw_input().split())
    for j in range(n):
        tmp = seq[j]
        if tmp != -1:
            x[(i, j)]=tmp
    status[i] = False

print mst(0, x)

Submission status: Wrong Answer

Solution code:
import sys
    
global status, d
status = {}
d=0

def mst(p1, GRAPH):
    global status
    
    edge={}
    total = 0
    mini = 0
    while True:
        status[p1]=True
        for p2 in range(len(status)):
            if status[p2]==False and GRAPH.has_key((p1,p2)):
                edge[(p1, p2)]=GRAPH[(p1, p2)]
        mini=10000
        for key, value in edge.items():
            if status[key[1]]==True:
                del edge[key]
                continue
            if value <mini:
                key0 = key
                mini = value
        if mini!=10000:
            total+=mini
            p1=key0[1]
        else:
            break
    
    return total

n = int(raw_input())
x = {}
for i in range(n):
    seq = map(int,raw_input().split())
    for j in range(n):
        tmp = seq[j]
        if tmp != -1:
            x[(i, j)]=tmp
    status[i] = False

print mst(0, x)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin, maxint


def main():
    num = int(stdin.readline())

    M = []
    for _ in xrange(num):
        M.append([int(s) for s in stdin.readline().split()])

    g = set(xrange(1, num+1))
    index = g.pop()
    h = {index}
    gravity = 0

    while g:
        minimum = maxint
        for j in h:
            for i, a in enumerate(M[j-1], 1):
                if i in h:
                    continue
                if 0 < a < minimum:
                    index = i
                    minimum = a
        h.add(index)
        g.remove(index)
        gravity += minimum

    print(gravity)


main()

Submission status: Time Limit Exceeded

Solution code:
def memoize(f):  
    cache = {}  
    def helper(x):  
        if x not in cache:              
            cache[x] = f(x)  
        return cache[x]  
    return helper 

def split_apex(a):
    if len(a) == 2:
        yield (a[0],), (a[1],)
    else:
        for i in range(0, len(a)):
            yield (a[i],), a[:i] + a[i + 1:]

@memoize
def wait(a):
    global g
    if len(a) == 1:
        return 0
    return min(calc_wait(apex, apices) for apex, apices in split_apex(a))

def calc_wait(apex, apices):
    global g
    w = [g[apex[0]][i] for i in apices if g[apex[0]][i] != -1]
    return  wait(apex) + wait(apices) + (min(w) if len(w) else 200000)

n = int(input())
g = [None] + [[None] + list(map(int, input().split())) for _ in range(n)]

a = tuple(i + 1 for i in range(n))
print(wait(a))

Submission status: Time Limit Exceeded

Solution code:
def Serch():
    unit = [2001]
    for j in Tree:
        for i in range(1, n):
            G[j][i] = int(G[j][i])
            if G[j][i] != -1 and i not in Tree:
                unit.append(G[j][i])
    for j in Tree:
        for i in range(1, n):
            if G[j][i] == min(unit) and i not in Tree:
                ans.append(int(G[j][i]))
                Tree.append(i)
                Serch()
                break


n = int(input())
G = []
for i in range(n):
    G.append(input().split())

ans = []
Tree = [0]
Serch()
print(sum(ans))

Submission status: Time Limit Exceeded

Solution code:
def Serch():
    unit = [2001]
    for j in Tree:
        for i in range(1, n):
            if G[j][i] != -1 and i not in Tree:
                unit.append(G[j][i])
    for j in Tree:
        for i in range(1, n):
            if G[j][i] == min(unit) and i not in Tree:
                ans.append(int(G[j][i]))
                Tree.append(i)
                Serch()
                break


n = int(input())
G = []
for i in range(n):
    G.append(input().split())
    for j in range(len(G[i])):
        G[i][j] = int(G[i][j])

ans = []
Tree = [0]
Serch()
print(sum(ans))

Submission status: Time Limit Exceeded

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[i]

print MST()

Submission status: Time Limit Exceeded

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[j]

print MST()

Submission status: Time Limit Exceeded

Solution code:
n = input()

INFTY = 10000000

color = [0 for i in xrange(n)]
M = [[INFTY 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] = G[j]

print MST()

Submission status: Time Limit Exceeded

Solution code:
n = input()

INFTY = 10000000

color = [0 for i in xrange(n)]
M = [[INFTY 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
    u = -1
    for i in xrange(n):
      if color[i] != 1 and d[i] < cost:
        cost = d[i]
        u = i

    if u == -1:
      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] = G[j]

print MST()

Submission status: Time Limit Exceeded

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

for i in range(n):
    inp = input()
    if "-1" in inp:
        inp = inp.replace("-1","10000")
    a.append(list(map(int, inp.split())))

w = 0
v = set(range(1,n))

edge    = [ 0, 0]
min_w   = [-1,-1]
min_idx = [-1,-1]

while v:
    min_w[0] = min(a[edge[0]])
    min_w[1] = min(a[edge[1]])
    min_idx[0] = a[edge[0]].index(min_w[0])
    min_idx[1] = a[edge[1]].index(min_w[1])
    if min_w[0] <= min_w[1]:
        k = 0
    else:
        k = 1
    if min_idx[k] not in v:
        a[edge[k]][min_idx[k]] = 10000
        continue
    else:
        w += min_w[k]
        v.remove(min_idx[k])
        edge[k] = min_idx[k]

print(w)

Submission status: Time Limit Exceeded

Solution code:
import sys
    
global status, d
status = {}
d=0

def mst(p1, GRAPH):
    global status
    
    edge={}
    total = 0
    mini = 0
    while True:
        status[p1]=True
        for p2 in range(len(status)):
            if status[p2]==False and GRAPH.has_key((p1,p2)):
                edge[(p1, p2)]=GRAPH[(p1, p2)]
                if mini<GRAPH[(p1,p2)]:
                    mini=GRAPH[(p1,p2)]
        for key, value in edge.items():
            if status[key[1]]==True:
                del edge[key]
                continue
            if value <mini:
                key0 = key
                mini = value
        if mini!=2000:
            total+=mini
            p1=key0[1]
        else:
            break
    
    return total

n = int(raw_input())
x = {}
for i in range(n):
    seq = map(int,raw_input().split())
    for j in range(n):
        tmp = seq[j]
        if tmp != -1:
            x[(i, j)]=tmp
    status[i] = False

print mst(0, x)

Submission status: Time Limit Exceeded

Solution code:
import sys
    
global status, d
status = {}
d=0

def mst(p1, GRAPH):
    global status
    
    edge={}
    total = 0
    mini = 0
    while True:
        status[p1]=True
        for p2 in range(len(status)):
            if status[p2]==False and GRAPH.has_key((p1,p2)):
                edge[(p1, p2)]=GRAPH[(p1, p2)]
                if mini<GRAPH[(p1,p2)]:
                    mini=GRAPH[(p1,p2)]+1
        for key, value in edge.items():
            if status[key[1]]==True:
                del edge[key]
                continue
            if value <mini:
                key0 = key
                mini = value
        if mini!=2000:
            total+=mini
            p1=key0[1]
        else:
            break
    
    return total

n = int(raw_input())
x = {}
for i in range(n):
    seq = map(int,raw_input().split())
    for j in range(n):
        tmp = seq[j]
        if tmp != -1:
            x[(i, j)]=tmp
    status[i] = False

print mst(0, x)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from collections import deque


class Graph:
    def __init__(self, n, adj_matrix, default_value=float('inf')):
        self.n = n
        self.adj_matrix = adj_matrix
        self.default_value = default_value

    def show(self):
        for _ in self.adj_matrix:
            print(*_)

    def set_mst(self, start=0):  # minimum spanning tree
        self.mst = []
        T = [start]

        for _ in range(self.n - 1):
            edges = [(cost, u, v) for u in T
                     for v, cost in enumerate(self.adj_matrix[u])
                     if cost != self.default_value and v not in T]

            min_cost, *min_edge = min(edges)
            self.mst.append(tuple(min_edge))
            T.append(min_edge[1])

    def show_mst(self):
        self.set_mst()
        print(sum([self.adj_matrix[u][v] for u, v in self.mst]))

    def dfs(self):
        self.states = [2] * self.n
        self.d = [None] * self.n
        self.f = [None] * self.n
        self.time = 0

        for u in range(self.n):
            if self.states[u] == 2:
                self.dfs_visit(u)

    def dfs_visit(self, u):
        self.states[u] = 1
        self.time += 1
        self.d[u] = self.time

        for v, edge in [(v, edge) for v, edge in enumerate(self.adj_matrix[u])
                        if edge]:
            if self.states[v] == 2:
                self.dfs_visit(v)

        self.states[u] = 0
        self.time += 1
        self.f[u] = self.time

    def show_dfs(self, start=0):
        self.dfs()
        for i, (d, f) in enumerate(zip(self.d, self.f)):
            print(i + 1, d, f)

    def bfs(self, start):
        self.states = [0] * self.n
        self.dists = [float('inf')] * self.n

        queue = deque([start])
        self.dists[start] = 0
        while queue:
            u = queue.popleft()
            edges = self.adj_matrix[u]

            for v, edge in [(v, edge) for v, edge in enumerate(edges) if edge]:
                if self.states[v]:
                    continue

                if self.dists[v] > self.dists[u] + 1:
                    self.dists[v] = self.dists[u] + 1
                queue.append(v)

                self.states[v] = 1

        self.dists = [
            -1 if dist == float('inf') else dist for dist in self.dists
        ]

    def show_bfs(self, start=0):
        self.bfs(start=start)
        for i, dist in enumerate(self.dists):
            print(i + 1, dist)


if __name__ == '__main__':
    n = int(input())
    adj_matrix = [[
        int(cost) if int(cost) != -1 else float('inf')
        for cost in input().split()
    ] for i in range(n)]

    g = Graph(n, adj_matrix)
    g.show_mst()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
def prim(edges, *, start=0, adj_matrix=False, default_value=float('inf')):
    '''
    Returns the Minimum Spanning Tree(MST) of a given graph

    # sample input when given as adjacency matrix
    edges = [[0, 2, 5, 4, inf, inf],           # node 0
             [2, 0, inf, 3, 6, inf],           # node 1
             [5, inf, 0, 2, inf, 6],           # node 2
             [4, 3, 2, 0, 2, inf],             # node 3
             [inf, 6, inf, 2, 0, 4],           # node 4
             [inf, inf, 6, inf, 4, 0]]         # node 5

    # sample input when given not as adjacency matrix
    edges = [[(1, 2), (2, 5), (3, 4)],         # node 0
             [(0, 2), (3, 3), (4, 6)],         # node 1
             [(0, 5), (3, 2), (5, 6)],         # node 2
             [(0, 4), (1, 3), (2, 2), (4, 2)], # node 3
             [(1, 6), (3, 2), (5, 4)],         # node 4
             [(2, 6), (4, 4)]]                 # node 5
    '''

    n = len(edges)
    mst = []
    cost = 0
    T = [start]

    while True:
        tmp_edges = [(cost, (u, v)) for u in T for v, cost in enumerate(edges[u]) if cost != default_value and v not in T] if adj_matrix else\
                    [(cost, (u, v)) for u in T for v, cost in edges[u] if v not in T]

        if tmp_edges:
            min_cost, min_edge = min(tmp_edges)
            mst.append(min_edge)
            cost += min_cost
            T.append(min_edge[1])

        else:
            if len(mst) != n - 1:
                raise NoSpanningError(
                    'There is no spanning tree in this graph (search started from node{})'.
                    format(start))

            else:
                return mst, cost


class NoSpanningError(Exception):
    pass


if __name__ == '__main__':
    '''
    an example of using this function
    AIZU ONLINE JUDGE - ALDS_1_12_A
    '''

    n = int(input())
    edges = [[int(cost) if int(cost) != -1 else float('inf') for cost in input().split()] for i in range(n)]

    print(prim(edges, adj_matrix=True)[1])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
def prim(edges, *, start=0, adj_matrix=False, default_value=float('inf')):
    '''
    Returns the Minimum Spanning Tree(MST) of a given graph

    # sample input when given not as adjacency list (generally works faster)
    edges = [[(1, 2), (2, 5), (3, 4)],         # node 0
             [(0, 2), (3, 3), (4, 6)],         # node 1
             [(0, 5), (3, 2), (5, 6)],         # node 2
             [(0, 4), (1, 3), (2, 2), (4, 2)], # node 3
             [(1, 6), (3, 2), (5, 4)],         # node 4
             [(2, 6), (4, 4)]]                 # node 5

    # sample input when given as adjacency matrix
    edges = [[0, 2, 5, 4, inf, inf],           # node 0
             [2, 0, inf, 3, 6, inf],           # node 1
             [5, inf, 0, 2, inf, 6],           # node 2
             [4, 3, 2, 0, 2, inf],             # node 3
             [inf, 6, inf, 2, 0, 4],           # node 4
             [inf, inf, 6, inf, 4, 0]]         # node 5
    '''

    n = len(edges)
    mst = []
    cost = 0
    T = [start]

    while True:
        tmp_edges = [(cost, (u, v)) for u in T for v, cost in enumerate(edges[u]) if cost != default_value and v not in T] if adj_matrix else\
                    [(cost, (u, v)) for u in T for v, cost in edges[u] if v not in T]

        if tmp_edges:
            min_cost, min_edge = min(tmp_edges)
            mst.append(min_edge)
            cost += min_cost
            T.append(min_edge[1])

        else:
            if len(mst) != n - 1:
                raise NoSpanningError(
                    'There is no spanning tree in this graph (search started from node{})'.
                    format(start))

            else:
                return mst, cost


class NoSpanningError(Exception):
    pass


if __name__ == '__main__':
    '''
    an example of using this function
    AIZU ONLINE JUDGE - ALDS_1_12_A
    '''

    n = int(input())
    edges = [[int(cost) if int(cost) != -1 else float('inf') for cost in input().split()] for i in range(n)]

    print(prim(edges, adj_matrix=True)[1])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
def prim(edges, *, start=0, adj_matrix=False, default_value=float('inf')):
    '''
    Returns the Minimum Spanning Tree(MST) of a given graph

    # sample input when given not as adjacency list (generally works faster)
    edges = [[(1, 2), (2, 5), (3, 4)],         # node 0
             [(0, 2), (3, 3), (4, 6)],         # node 1
             [(0, 5), (3, 2), (5, 6)],         # node 2
             [(0, 4), (1, 3), (2, 2), (4, 2)], # node 3
             [(1, 6), (3, 2), (5, 4)],         # node 4
             [(2, 6), (4, 4)]]                 # node 5

    # sample input when given as adjacency matrix
    edges = [[0, 2, 5, 4, inf, inf],           # node 0
             [2, 0, inf, 3, 6, inf],           # node 1
             [5, inf, 0, 2, inf, 6],           # node 2
             [4, 3, 2, 0, 2, inf],             # node 3
             [inf, 6, inf, 2, 0, 4],           # node 4
             [inf, inf, 6, inf, 4, 0]]         # node 5
    '''

    n = len(edges)
    mst = []
    cost = 0
    T = [start]

    while True:
        tmp_edges = [(cost, (u, v)) for u in T for v, cost in enumerate(edges[u]) if cost != default_value and v not in T] if adj_matrix else\
                    [(cost, (u, v)) for u in T for v, cost in edges[u] if v not in T]

        if tmp_edges:
            min_cost, min_edge = min(tmp_edges)
            mst.append(min_edge)
            cost += min_cost
            T.append(min_edge[1])

        else:
            if len(mst) != n - 1:
                raise NoSpanningError(
                    'There is no spanning tree in this graph (search started from node{})'.
                    format(start))

            else:
                return mst, cost


class NoSpanningError(Exception):
    pass


if __name__ == '__main__':
    '''
    an example of using this function
    AIZU ONLINE JUDGE - ALDS_1_12_A
    '''

    n = int(input())
    edges = [[(j, int(cost)) for j, cost in enumerate(input().split()) if int(cost) != -1] for i in range(n)]

    print(prim(edges)[1])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from heapq import heappop, heappush


def prim(edges, *, start=0, adj_matrix=False, default_value=float('inf')):
    '''
    Returns the Minimum Spanning Tree(MST) of a given graph

    # sample input when given not as adjacency list (adj_matrix=False) (generally works faster)
    edges = [[(1, 2), (2, 5), (3, 4)],         # node 0
             [(0, 2), (3, 3), (4, 6)],         # node 1
             [(0, 5), (3, 2), (5, 6)],         # node 2
             [(0, 4), (1, 3), (2, 2), (4, 2)], # node 3
             [(1, 6), (3, 2), (5, 4)],         # node 4
             [(2, 6), (4, 4)]]                 # node 5

    # sample input when given as adjacency matrix (adj_matrix=True)
    edges = [[0, 2, 5, 4, inf, inf],           # node 0
             [2, 0, inf, 3, 6, inf],           # node 1
             [5, inf, 0, 2, inf, 6],           # node 2
             [4, 3, 2, 0, 2, inf],             # node 3
             [inf, 6, inf, 2, 0, 4],           # node 4
             [inf, inf, 6, inf, 4, 0]]         # node 5
    '''

    n = len(edges)

    costs = [float('inf')] * n
    costs[start] = 0
    prevs = [-1] * n

    pq = [(0, start)]
    T = [True] * n

    while pq:
        tmp_cost, tmp_node = heappop(pq)
        T[tmp_node] = False

        nxt_edges = ((node, cost) for node, cost in enumerate(edges[tmp_node]) if cost != default_value and T[node]) if adj_matrix else\
                    ((node, cost) for node, cost in edges[tmp_node] if T[node])

        for nxt_node, nxt_cost in nxt_edges:
            if costs[nxt_node] > nxt_cost:
                costs[nxt_node] = nxt_cost
                prevs[nxt_node] = tmp_node
                heappush(pq, (nxt_cost, nxt_node))
                T[nxt_node] = True

    else:
        if len([prev for prev in prevs if prev != -1]) != n - 1:
            raise NoSpanningError(
                'There is no spanning tree in this graph (search started from node{})'.
                format(start))

        else:
            return prevs, costs


class NoSpanningError(Exception):
    pass


if __name__ == '__main__':
    '''
    an example of using this function
    AIZU ONLINE JUDGE - ALDS_1_12_A
    '''

    n = int(input())
    edges = [[(j, int(cost)) for j, cost in enumerate(input().split())
              if int(cost) != -1] for i in range(n)]

    prevs, costs = prim(edges)
    print(sum(costs))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from heapq import heappop, heappush


def prim(edges, *, start=0, adj_matrix=False, default_value=float('inf')):
    n = len(edges)

    costs = [float('inf')] * n
    costs[start] = 0
    prevs = [-1] * n

    pq = [(0, start)]
    T = [True] * n

    while pq:
        tmp_cost, tmp_node = heappop(pq)
        T[tmp_node] = False

        nxt_edges = ((node, cost) for node, cost in enumerate(edges[tmp_node]) if cost != default_value and T[node]) if adj_matrix else\
                    ((node, cost) for node, cost in edges[tmp_node] if T[node])

        for nxt_node, nxt_cost in nxt_edges:
            if costs[nxt_node] > nxt_cost:
                costs[nxt_node] = nxt_cost
                prevs[nxt_node] = tmp_node
                heappush(pq, (nxt_cost, nxt_node))
                T[nxt_node] = True

    else:
        if len([prev for prev in prevs if prev != -1]) != n - 1:
            raise NoSpanningError(
                'There is no spanning tree in this graph (search started from node{})'.
                format(start))
        else:
            return prevs, costs


class NoSpanningError(Exception):
    pass


if __name__ == '__main__':
    n = int(input())
    edges = [[(j, int(cost)) for j, cost in enumerate(input().split())
              if int(cost) != -1] for i in range(n)]

    prevs, costs = prim(edges)
    print(sum(costs))

Submission status: Accepted

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 > -1 and not i in DP:
            heapq.heappush(h,(j,i))
print(c)

Submission status: Accepted

Solution code:
import sys
def prim(n, m):
	d = [sys.maxsize]*n
	p = [-1]*n
	c = [False]*n
	d[0] = 0
	while True:
		minv = sys.maxsize
		u = -1
		for i in range(n):
			if minv > d[i] and c[i] == False:
				minv = d[i]
				u = i
		if u == -1:
			break
		c[u] = True
		for i in range(n):
			if m[u][i] != sys.maxsize:
				if m[u][i] < d[i] and c[i] == False:
						d[i] = m[u][i]
						p[i] = u
	sum = 0
	for i in range(n):
		if p[i] != -1:
			sum += m[i][p[i]]
	return sum

n = int(input())
m = [[0 for x in range(n)] for x in range(n)]
for i in range(n):
	a = list(map(int, input().split()))
	for j in range(n):
		if a[j] == -1:
			m[i][j] = sys.maxsize
		else:
			m[i][j] = a[j]
print(prim(n, m))

Submission status: Accepted

Solution code:
#coding: utf-8

inf = 1000000000
n = int(input())
mtrx = []
for i in range(n):
    col2 = list(map(int,input().split()))
    col = []
    for num in col2:
        if num == -1:
            num = inf
        col.append(num)
    mtrx.append(col)

def prim():
    color = ["white" for i in range(n)]
    d = [inf for i in range(n)]
    p = [None for i in range(n)]
    p[0] = -1
    d[0] = 0

    while True:
        mincost = inf
        for i in range(n):
            if color[i] != "black" and d[i] < mincost:
                mincost = d[i]
                u = i

        if mincost == inf:
            break

        color[u] = "black"

        for v in range(n):
            if color[v] != "black" and mtrx[u][v] != inf:
                if mtrx[u][v] < d[v]:
                    d[v] = mtrx[u][v]
                    p[v] = u
                    color[v] = "gray"
    print(sum(d))

prim()

Submission status: Accepted

Solution code:

def judge_reachable(graph,start,end,flag):
    flag[start]=1
    for vertex in graph[start]:
        if(flag[vertex]==1):
            continue
        if (vertex==end):
            return 1
        if(judge_reachable(graph,vertex,end,flag)):
            return 1
    return 0



graph_n=int(input())


edge_dict={}



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


sorted_edge=sorted(edge_dict.items())


graph=[[] for i in range(graph_n)]

edge_num=0
cost=0

for edges in sorted_edge:
    for edge in edges[1]:
        flag=[0]*graph_n
        if(judge_reachable(graph,edge[0],edge[1],flag)==0):
            graph[edge[0]].append(edge[1])
            graph[edge[1]].append(edge[0])
            edge_num+=1
            cost+=edges[0]
            if(edge_num ==graph_n - 1):
                break    
    if(edge_num ==graph_n -1):
        break

print(cost)

Submission status: Accepted

Solution code:
from sys import stdin

def read_matrix(n):
    A = []
    for _ in range(n):
        a = [ int(i) for i in stdin.readline().strip().split() ]
        A.append(a)
    return A

def prim(n, A):
    color = [ 'WHITE' for i in range(n) ]
    d = [ float('inf') for i in range(n) ]
    d[0] = 0
    p = [-1] * n

    while True:
        mincost = float('inf')
        for i in range(n):
            if color[i] != 'BLACK' and d[i] < mincost:
                mincost = d[i]
                u = i

        if mincost == float('inf'):
            break

        color[u] = 'BLACK'

        for v in range(n):
            if color[v] != 'BLACK' and A[u][v] != -1:
                if A[u][v] < d[v]:
                    d[v] = A[u][v]
                    p[v] = u
                    color[v] = 'GRAY'

    return sum(d)

n = int(input())
A = read_matrix(n)
print(prim(n, A))

Submission status: Accepted

Solution code:
n = int(input())
m = [[-1 for i in range(n)] for j in range(n)] #お隣さんへのコストを保存（この中から最小を探す）

v = set()
v.add(0)

for i in range(n): #隣接の辺のコストを入力
  nums = list(map(int, input().split()))
  for j in range(n):
    m[i][j] = nums[j]


def prim_mst(n):
  isVisited = [False] * n
  d = [0] + [2001] * (n-1)      #TとV-Tのを繋ぐ最小辺の重みを格納する

  while  True:
    mincost = 2001
    for i in range(n):
      if not (isVisited[i]) and d[i] < mincost:
        mincost = d[i]
        u = i
    isVisited[u] = True


    if mincost == 2001:        #mincostが2001になったら繰り返し作業終了
      break

    for v in range (n):
      if (not isVisited[v]) and (m[u][v] != -1):
        if m[u][v] < d[v]:
          d[v] = m[u][v]
  print(sum(d))

prim_mst(n)