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

Solution (Python):


n = input()

M = [[float("inf") for j in xrange(n)] for i in xrange(n)]
color = ['WHITE' for i in xrange(n)]
d = [float("inf") for i in xrange(n)]
p = [-1 for i in xrange(n)]

for i in xrange(n):
    tmp = map(int, raw_input().split())
    for j in xrange(n):
        if tmp[j] != -1:
            M[i][j] = tmp[j]

d[0] = 0
p[0] = -1

while 1:
    mincost = float("inf")
    for i in xrange(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 xrange(n):
        if color[v] != "BLACK" and M[u][v] != -1 and M[u][v] < d[v]:
            d[v] = M[u][v]
            p[v] = u
            color[v] = "GRAY"


sum = 0

for i in xrange(n):
    sum += d[i]

print sum

Solution (Python):
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] != 2 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 and 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()

Solution (Python):
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 )
    p.remove( add_A )
    l += a_min
print l

Solution (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}
    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
 
    print(weight)
 
 
main()

Solution (Python):
n = int(raw_input())
A = [0]
B = range(1, n)
a = [[0 for i in xrange(0,n)] for j in xrange(0,n)]

for i in xrange(0,n):
 a[i] = map(int,raw_input().split())

count = 0
while B != []:
 smin = 2001
 for i in A:
  for j in B:
   if 0 <= a[i][j] < smin:
    smin = a[i][j]
    addA = j
 A.append(addA)
 B.remove(addA)
 count += smin

print count

Solution (Python):
from __future__ import division, print_function
from sys import stdin, maxint
 
 
def main():
    x = int(stdin.readline())
 
    y = []
    for _ in xrange(x):
        y.append([int(s) for s in stdin.readline().split()])
 
    g = set(xrange(1, x+1))
    index = g.pop()
    h = {index}
    leng = 0
 
    while g:
        minimum = maxint

        for j in h:
            mj = y[j-1]
            for i in g:
                if 0 <= mj[i-1] < minimum:
                    index = i
                    minimum = mj[i-1]

        h.add(index)
        g.remove(index)
        leng += minimum
 
    print(leng)
 
 
main()

Solution (Python):
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
    A.append(AA)
    B.remove(AA)
    omomi=omomi+c
 
print omomi

Solution (Python):
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)

Solution (Python):
n = int(raw_input())
g = [[10000 for i in range(n)]for j in range(n)]
c = [0 for i in range(n)]
d = [10000 for i in range(n)]
p = [-1 for i in range(n)]
d[0] = 0
for i in range(n):
        g[i] = map(int,raw_input().split())

while 1:
    min = 10000
    u = -1
    for i in range(n):
        if c[i] != 2 and d[i] < min:
            min = d[i]
            u = i
    if min == 10000:
        break
    c[u] = 2
    
    for v in range(n):
        if c[v] != 2 and g[u][v] != -1:
            if g[u][v] < d[v]:
                d[v] = g[u][v]
                p[v] = u
                c[v] = 1
    sum = 0
    for i in range(n):
        if p[i] != -1:
            sum += g[i][p[i]]
print sum

Solution (Python):
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)]
p = [-1 for i in range(n)]
 
def MST():
  d[0] = 0
 
  while True:
    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]
        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] = G[j]
 
print MST()

Solution (Python):
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)

Solution (Python):
n = input()
M = []
inf = 1000000000
for i in range(n):
  M.append(map(int, raw_input().split()))
for i in range(n):
  for j in range(n):
    if M[i][j]==-1:
      M[i][j] = inf
d = [inf for i in range(n)]
p = [-1 for i in range(n)]
color = [0 for i in range(n)]

d[0] = 0

while 1:
  minv = inf
  u = -1
  for i in range(n):
    if minv>d[i] and color[i]!=2:
      u = i
      minv = d[i]
  if u == -1:
    break
  color[u] = 2
  for v in range(n):
    if color[v]!=2 and M[u][v]!=inf:
      if d[v]>M[u][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]]
print sum

Solution (Python):
n = int(raw_input())
A = [0]
NY = 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())
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

Solution (Python):
n = input()
 
M = [[float("inf") for j in xrange(n)] for i in xrange(n)]
color = ['WHITE' for i in xrange(n)]
d = [float("inf") for i in xrange(n)]
p = [-1 for i in xrange(n)]
 
for i in xrange(n):
    tmp = map(int, raw_input().split())
    for j in xrange(n):
        if tmp[j] != -1:
            M[i][j] = tmp[j]
 
d[0] = 0
p[0] = -1
 
while 1:
    mincost = float("inf")
    for i in xrange(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 xrange(n):
        if color[v] != "BLACK" and M[u][v] != -1 and M[u][v] < d[v]:
            d[v] = M[u][v]
            p[v] = u
            color[v] = "GRAY"
 
 
sum = 0
 
for i in xrange(n):
    sum += d[i]
 
print sum

Solution (Python):
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=1000000
        for key, value in edge.items():
            if status[key[1]]==True:
                del edge[key]
                continue
            if value <mini:
                key0 = key
                mini = value
        if mini!=1000000:
            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)

Solution (Python):
n = int(raw_input())
A = [0]
p = range(1, n)
a = [[0 for i in range(n)]for j in range(n)]

for i in range(n):
    a[i] = map(int, raw_input().split() )

l = 0

while p != []:
    a_min = 10000
    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)
    p.remove(add_A)
    l += a_min

print l

Solution (Python):
n = input()
A = [0]
p = range(1, n)
a = [[0 for i in range(n)]for j in range(n)]

for i in range(n):
    a[i] = map(int, raw_input().split() )

l = 0

while p != []:
    a_min = 10000
    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)
    p.remove(add_A)
    l += a_min

print l

Solution (Python):
n = input()
A = [0]
p = range(1, n)
a = [[0 for i in range(n)]for j in range(n)]

for i in range(n):
    a[i] = map(int, raw_input().split() )

l = 0

while p != []:
    a_min = 10000
    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)
    p.remove(add_A)
    l += a_min

print l

Solution (Python):
MAX = 100
INF = 1000000
WHITE = 0
GRAY = 1
BLACK = 2
n = int(raw_input())

M = [[0 for i in range(n)]for j in range(n)]
d = [0 for i in range(MAX)]
p = [0 for i in range(MAX)]
Color = [0 for i in range(MAX)]
for i in range(n):
    a = map(int, raw_input().split())
    for j in range(n):
        e = a[j]
        if e == -1:
            M[i][j] = INF
        else:
            M[i][j] = e


for i in range(n):
    d[i] = INF
    p[i] = -1
    Color[i] = WHITE
d[0] = 0
    
while True:
    minv = INF
    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] != INF:
            if d[v] > M[u][v]:
                d[v] = M[u][v]
                p[v] = u
                Color[v] = GRAY
sum = 0
for i in range(n):
    if p[i] != -1:
        sum += M[i][p[i]]
print sum

Solution (Python):
class Node(object):
    def __init__(self, V):
        self.V = V
        self.d = float('inf')
        self.p = -1
        self.state = -1
        
        
        


M = [float('inf')] * 100
for i in range(100):
    M[i] = [float('inf')] * 100

n = int(input())
nodes = [0] * 100
for i in range(n):
    V = [int(x) for x in input().split()] 
    for (j,m) in enumerate(V):
        M[i][j] = m if not m == -1 else float('inf') 
    nodes[i] = Node([])

nodes[0].d = 0
while True:
    mincost = float('inf')
    u = -1
    for i in range(n):
        node = nodes[i]
        if (mincost > node.d) and (node.state != 1):
            u = i
            mincost = node.d

    if u == -1:
        break

    nodes[u].state = 1
    for v in range(n):
        node = nodes[v]
        if (node.state != 1) and (M[u][v] != float('inf')):
            if node.d > M[u][v]:
                node.d = M[u][v]
                node.p = u
                node.state = 0

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

print(sum)

Solution (Python):
n = input()
 
inf = 10000000
 
color = [0 for i in xrange(n)]
M = [[inf for i in xrange(n)] for i in xrange(n)]
d = [inf for i in xrange(n)]
p = [-1 for i in xrange(n)]
 
def mst():
  d[0] = 0
 
  while True:
    cost = inf
    for i in xrange(n):
      if color[i] != 2 and d[i] < cost:
        cost = d[i]
        u = i
 
    if cost == inf:
      break
     
    color[u] = 2
 
    for v in xrange(n):
      if color[v] != 2 and M[u][v] != inf and 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()

Solution (Python):
import heapq

n = int(input())
edges = [set((w, j) for j, w in enumerate(map(int, input().split())) if w > -1) for _ in range(n)]


def get_minimum():
    global n, edges
    visited = [False] * n
    visited[0] = True
    queue = list(edges[0])
    heapq.heapify(queue)
    total_cost = 0
    while queue:
        cost, vertex = heapq.heappop(queue)
        if visited[vertex]:
            continue
        visited[vertex] = True
        total_cost += cost
        if sum(visited) == n:
            return total_cost
        queue.extend(edges[vertex])
        heapq.heapify(queue)


print(get_minimum())

Solution (Python):
import heapq

n = int(input())
edges = [set((w, j) for j, w in enumerate(map(int, input().split())) if w > -1) for _ in range(n)]

visited = [False] * n
visited[0] = True
queue = list(edges[0])
heapq.heapify(queue)
total_cost, remains = 0, n - 1
while True:
    cost, vertex = heapq.heappop(queue)
    if visited[vertex]:
        continue
    visited[vertex] = True
    total_cost += cost
    remains -= 1
    if not remains:
        break
    queue.extend(edges[vertex])
    heapq.heapify(queue)

print(total_cost)

Solution (Python):
import heapq

n = int(input())
edges = [set((w, j) for j, w in enumerate(map(int, input().split())) if w > -1) for _ in range(n)]

visited = [False] * n
visited[0] = True
queue = list(edges[0])
heapq.heapify(queue)
total_cost, remains = 0, n - 1
while True:
    cost, vertex = heapq.heappop(queue)
    if visited[vertex]:
        continue
    visited[vertex] = True
    total_cost += cost
    remains -= 1
    if not remains:
        break
    for t in edges[vertex]:
        if not visited[t[1]]:
            heapq.heappush(queue, t)

print(total_cost)

Solution (Python):
infty = 10**21
white = 0
gray = 1
black = 2
n = input()
m = [[0 for i in xrange(n)] for j in xrange(n)]
l = m
d = [0 for i in xrange(n)]
p = [0 for i in xrange(n)]
color = [0 for i in xrange(n)]


def prim():
    
    
    for i in xrange(n):
        d[i] = infty
        p[i] = -1
        color[i] = white

    d[0] = 0
    
    while True:
        minv = infty
        u = -1
        for i in xrange(n):
            if minv > d[i] and color[i] != black:
                u = i
                minv = d[i]
        if u == -1:
            break
        color[u] = black
        for v in xrange(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
    sum = 0
    for i in xrange(n):
        if p[i] != -1:
            sum += m[i][p[i]]
    return sum

for i in xrange(n):
    for j in xrange(n):
        if j == 0:
            l[i] = map(int,raw_input().split())
        if l[i][j] == -1:
            m[i][j] = infty
        else:
            m[i][j] = l[i][j]
print prim()

Solution (Python):
n = input()
A = [0]
p = range(1, n)
a = [[0 for i in range(n)]for j in range(n)]
 
for i in range(n):
    a[i] = map(int, raw_input().split() )
 
l = 0
 
while p != []:
    a_min = 10000
    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)
    p.remove(add_A)
    l += a_min
 
print l

Solution (Python):
class UnionFindTree:
    """Disjoint-Set Data Structure
       Union-Find Tree
       complexity:
          init: O(n)
          find, unite, same: O(alpha(n))
       used in SRM505 div.2 900, ATC001 A, DSL1A(AOJ)
    """
    def __init__(self, n):
        self.par = list(range(n))  
        self.rank = [0] * n  

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

    def unite(self, x, y):
        x, y = self.find(x), self.find(y)
        if x == y:
            return
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

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


class Kruskal:
    """ Kruskal's algorithm: find minimum spanning tree
        Complexity: O(E log(V))
        used in GRL2A(AOJ)
    """

    def __init__(self, V, E, start=0, INF=10**9):
        """ V: the number of vertexes
            E: adjacency list (undirected graph)
        """
        self.kruskal(V, E)

    def kruskal(self, V, E):
        edges = []
        for v1 in range(V):
            for v2, cost in E[v1]:
                if v1 < v2:
                    edges.append((cost, v1, v2))
        edges.sort(reverse=True)
        self.mincost = 0
        self.minSpanningTree = []
        uf = UnionFindTree(V)
        while len(self.minSpanningTree) < V-1:
            cost, v1, v2 = edges.pop()
            if uf.same(v1, v2) == False:
                self.mincost += cost
                uf.unite(v1, v2)
                self.minSpanningTree.append((v1, v2, cost))

    def minCost(self):
        return self.mincost

    def getMinSpanningTree(self):
        return sorted(self.minSpanningTree)

V = int(input())
edge = [[] for _ in range(V)]
for i in range(V):
    for j, d in enumerate(map(int, input().split())):
        if d != -1:
            edge[i].append((j, d))
mst = Kruskal(V, edge)
print(mst.minCost())

Solution (Python):
import heapq


class MinimumSpanningTree:
    """ Prim's algorithm: find minimum spanning tree
        Complexity: O(E log(V))
        used in GRL2A(AOJ)
    """

    def __init__(self, V, E, start=0, INF=10**9):
        """ V: the number of vertexes
            E: adjacency list (undirected graph)
            start: start vertex
            INF: Infinity cost
        """
        self.prim(V, E, start, INF)

    def prim(self, V, E, start=0, INF=10**9):
        used = [False] * V
        self.mincost = 0
        que = []
        heapq.heappush(que, (0, 0))
        while len(que) > 0:
            cost, v = heapq.heappop(que)
            if used[v]:
                continue
            used[v] = True
            self.mincost += cost
            for to, c in E[v]:
                heapq.heappush(que, (c, to))

    def minCost(self):
        return self.mincost

V = int(input())
edge = [[] for _ in range(V)]
for i in range(V):
    for j, d in enumerate(map(int, input().split())):
        if d != -1:
            edge[i].append((j, d))
mst = MinimumSpanningTree(V, edge)
print(mst.minCost())

Solution (Python):
def kruskal(n):
    cost = []
    tree = [{i} for i in range(n)]
    while edge:
        cmin = min(weight)
        index = weight.index(cmin)
        i, j = edge[index]
        del weight[index], edge[index]
        for t in tree:
            if {i, j} <= t:
                break
        else:
            cost.append(cmin)
            for n in range(len(tree)):
                if i in tree[n]:
                    tmp = tree[n]
                    del tree[n]
                    break
            for n in range(len(tree)):
                if j in tree[n]:
                    tree[n] |= tmp
                    break
    return sum(cost)

n = int(input())
edge = []
weight = []
for i in range(n):
    for j, c in enumerate(map(int, input().split())):
        if c != -1 and not {i, j} in weight:
            edge.append({i, j})
            weight.append(c)
print(kruskal(n))

Solution (Python):
def prim():
    global n
    global ct
    color=[0]*n
    d=[float('inf')]*n
    d[0]=0
    while True:
        mincost=float('inf')
        for i in xrange(n):
            if color[i]!=2 and d[i]<mincost:
                mincost=d[i]
                u=i
        if mincost==float('inf'):
            break
        ct+=d[u]
        color[u]=2
        for v in xrange(n):
            if color[v]!=2 and m[u][v]!=-1:
                if m[u][v]<d[v]:
                    d[v]=m[u][v]
                    color[v]=1
    
if __name__=='__main__':
    n=input()
    m=[map(int,raw_input().split()) for _ in xrange(n)]
    ct=0
    prim()
    print(ct)

Solution (Python):
MAX = 100
INF = 1 << 21
WHITE = 0 
GRAY = 1  
BLACK = 2 

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

for i in range(n):
    for j in range(n):
        if M[i][j] == -1:
            M[i][j] = INF

d = [INF for i in range(n)] 
p = [-1 for i in range(n)]  
color = [WHITE for i in range(n)]

def prim():
    global M, d, p, color

    d[0] = 0

    while(1):
        minv, u = INF, -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] != INF:
                if d[v] > M[u][v]:
                    d[v], p[v], color[v] = M[u][v], u, GRAY
    return sum([M[i][p[i]] for i in range(n) if p[i] != -1])


print(prim())

Solution (Python):
import sys

def prim(E):
    V = [0]
    for i in range(len(E)):
        E[i][0] = -1
    n = len(E)
    sum = 0

    while len(V) != n:
        mini, minj, mine = -1, -1, 2001
        for i in V:
            for j in range(len(E[i])):
                if E[i][j] != -1 and E[i][j] < mine:
                    mini, minj, mine = i, j, E[i][j]
        V.append(minj)
        for i in range(len(E)):
            E[i][minj] = -1
        sum += mine

    return sum

lines = sys.stdin.readlines()
del lines[0]

E = []
for line in lines:
    E.append(map(int, line.split()))

print prim(E)

Solution (Python):
n = int(input())

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

def mst():
    T = [0]
    gross_weight = 0
    cnt = n - 1
    while cnt:
        ew = 2001
        for i in range(len(T)):
            for tv, tew in enumerate(adj[T[i]]):
                if (tv not in T) and (tew != -1):
                    if tew < ew:
                        v, ew = tv, tew
        T.append(v)
        gross_weight += ew
        cnt -= 1
    print(gross_weight)


mst()

Solution (Python):
n = int(input())

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


def prim_mst(vn):
    isVisited = [False] * vn
    d = [0] + [2001] * (vn - 1)
    p = [-1] * vn

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

        if mincost == 2001:
            break

        isVisited[u] = True

        for v in range(vn):
            if (not isVisited[v]) and (adj[u][v] != -1):
                if adj[u][v] < d[v]:
                    d[v] = adj[u][v]
                    p[v] = u

    print(sum(d))


prim_mst(n)

Solution (Python):

level = False
def debug(v):
    if level:
        print(v)

n = int(input())
g = []

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

debug(g)

def prim(n):
    visited = [False] * n
    d = [0] + [2001] * (n - 1)
    p = [-1] * n

    while True:
        mincost = 2001

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

        for v in range(n):
            if (not visited[v]) and (g[u][v] != -1):
                if g[u][v] < d[v]:
                    d[v] = g[u][v]
                    p[v] = u

    print(sum(d))

prim(n)

Solution (Python):
def prim():
    global M
    global n
    global INF
    color = ['w' for i in range(n)]
    d = [INF for i in range(n)]
    d[0] = 0
    p = [-1 for i in range(n)]

    while True:
        mincost = INF
        u = -1
        for i in range(n):
            if color[i] != 'b' and d[i] < mincost:
                mincost = d[i]
                u = i
        if u == -1:
            break
        color[u] = 'b'
        for v in range(n):
            if color[v] != 'b' and M[u][v] != INF:
                if M[u][v] < d[v]:
                    d[v] = M[u][v]
                    p[v] = u
                    color[v] = 'g'
    s = 0
    for i in range(n):
        if p[i] != -1:
            s += M[i][p[i]]
    return s


INF = 3000
n = int(input())

M = [[0 for j in range(n)] for i in range(n)]

for i in range(n):
    for j, x in enumerate(list(map(int, input().split()))):
        if x == -1:
            M[i][j] = INF
        else:
            M[i][j] = x
s = prim()
print(s)

Solution (Python):



import sys

WHITE, GRAY, BLACK = 0, 1, 2


def prim_span_tree():
    min_weight_vertices[0] = 0

    while True:
        min_cost = 2001
        current_vertex = -1
        for i in range(vertices_num):
            if color[i] != BLACK and min_weight_vertices[i] < min_cost:
                min_cost = min_weight_vertices[i]
                current_vertex = i

        if min_cost == 2001:
            break

        color[current_vertex] = BLACK

        for j in range(vertices_num):
            v_weight = int(init_vertices_matrix[current_vertex][j])
            if color[j] != BLACK and v_weight >= 0:
                if v_weight < min_weight_vertices[j]:
                    min_weight_vertices[j] = v_weight
                    parent_list[j] = current_vertex
                    color[j] = GRAY

    return min_weight_vertices


if __name__ == '__main__':
    _input = sys.stdin.readlines()
    vertices_num = int(_input[0])
    init_vertices_matrix = list(map(lambda x: x.split(), _input[1:]))

    parent_list, min_weight_vertices = [-1] * vertices_num, [2001] * vertices_num
    color = [WHITE] * vertices_num
    ans = prim_span_tree()
    print(sum(ans))

Solution (Python):
a=input()
matrix=[]
for i in range(int(a)):
	matrix.append(list(map(int,input().split())))


class union_find(object):
 	"""union-find tree"""
 	def __init__(self, length):
 		self.length = length
 		self.unionnumber=0
 		self.unionlist=[[]]
 		self.num=list(-1 for i in range(length))

 	def unite(self,i,j):
 		if self.num[i]==-1:
 			if self.num[j]==-1:
 				self.unionlist[self.unionnumber].extend([i,j])
 				self.num[i]=self.unionnumber
 				self.num[j]=self.unionnumber
 				self.unionnumber+=1
 				self.unionlist.append([])
 			else:
 				tmp=i 
 				i=j 
 				j=tmp 
 		if self.num[i]!=-1:
 			if self.num[j]!=-1:
 				if self.num[i]==self.num[j]:
 					pass
 				else:
 					self.unionlist[self.num[i]].extend(self.unionlist[self.num[j]])
 					tmp=self.num[j]
 					for k in self.unionlist[self.num[j]]:
 						self.num[k]=self.num[i]
 					self.unionlist[tmp]="del"
 			else:
 				self.num[j]=self.num[i]
 				self.unionlist[self.num[i]].append(j)

 	def same(self,i,j):
 		if self.num[i]==-1 or self.num[j]==-1:
 			return(False)
 		else:
 			return(self.num[i]==self.num[j])


def Kruskal(matrix):
	length=len(matrix)
	edgelist=[]
	for i in range(length):
		for j in range(i+1):
			if matrix[i][j]!=-1:
				edgelist.append([j,i,matrix[i][j]])
	edgelist.sort(key=lambda x:x[2],reverse=True)
	result=[[-1 for i in range(length)] for j in range(length)]
	union=union_find(length)
	while(edgelist!=[]):
		edge=edgelist.pop()
		i,j,score=edge
		if union.same(i,j):
			pass
		else:
			union.unite(i,j)
			result[i][j]=score
			result[j][i]=score
		
	return(result)

a=Kruskal(matrix)
count=0
for i in range(len(a)):
	for j in range(i):
		if a[i][j]!=-1:
			count+=a[i][j]

print(count)

Solution (Python):


def prim(n,G):
    dist=0
    visited=[False]*n
    cost=[1000000]*n
    pi=[0]*n
    cost[0]=0
    pi[0]=-1
    while True:
        mincost=1000000
        u=0
        for i in range(n):
            if visited[i]==False and cost[i]<mincost:
                mincost=cost[i]
                u=i
        if mincost==1000000:
            break
        visited[u]=True

        for i in range(n):
            if visited[i]==True or G[u][i]==-1:
                continue
            if G[u][i]<cost[i]:
                cost[i]=G[u][i]
                pi[i]=u
    print(sum(cost))
    
if __name__=="__main__":
    n=int(input())
    G=[]
    for i in range(n):
        G.append(list(map(int,input().split())))
    prim(n,G)