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:
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 19:11:44 2018

@author: maezawa
"""

n = int(input())
m = []
for i in range(n):
    mi = list(map(int, input().split()))
    m.append(mi)

#print(*m, sep='\n')

color = [0]*n
d = [10**9]*n
p = [0]*n
p[0] = -1

def prim():
    while True:
        mincost = 10**9
        for i in range(n):
            if color[i] != 2 and d[i] < mincost:
                mincost = d[i]
                u = i
        if mincost == 10**9:
            break

        color[u] = 2

        for v in range(n):
            if color[v] != 2 and m[u][v] != -1:
                if m[u][v] < d[v]:
                    d[v] = m[u][v]
                    p[v] = u
                    color[v] = 1
    sumw = 0
    for i in range(n):
        if p[i] != -1:
            sumw += m[i][p[i]]
    return sumw

print(prim())

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 14 19:11:44 2018

@author: maezawa
"""
infinity = 10**9

n = int(input())
m = []
for i in range(n):
    mi = list(map(int, input().split()))
    m.append(mi)

print(*m, sep='\n')

color = [0]*n
d = [10**9]*n
p = [0]*n
p[0] = -1
d[0] = 0

def prim():
    while True:
        mincost = 10**9
        for i in range(n):
            if color[i] != 2 and d[i] < mincost:
                mincost = d[i]
                u = i
        if mincost == 10**9:
            break

        color[u] = 2

        for v in range(n):
            if color[v] != 2 and m[u][v] != -1:
                if m[u][v] < d[v]:
                    d[v] = m[u][v]
                    p[v] = u
                    color[v] = 1
    sumw = 0
    for i in range(n):
        if p[i] != -1:
            sumw += m[i][p[i]]
    return sumw

print(prim())

Submission status: Wrong Answer

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):
            u, (v, cost) = min(
                [(u,
                  min([(i, cost) for i, cost in enumerate(self.adj_matrix[u])
                       if cost != self.default_value],
                      key=lambda x: x[1])) for u in T],
                key=lambda x: x[1][1])
            self.mst.append((u, v))
            T.append(v)

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

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)

    prevs = [-1] * n
    costs = [float('inf')] * n
    costs[start] = 0
    pq = [(0, start)]
    T = [True] * n
    rem = n - 1

    while pq and rem:
        tmp_cost, tmp_node = heappop(pq)
        T[tmp_node] = False
        rem -= 1

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

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

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

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(True):
    tmp = heapq.heappop(h)
    if tmp[1] in DP:
        continue
    c += tmp[0]
    DP[tmp[1]] = 1
    if len(DP) == n:
        break
    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: Wrong Answer

Solution code:
n = int(input())
m = [[-1 for i in range (n)] for j in range(n)]
d = [0]+ [2000]* (n-1)
isVisited = [False] * n


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

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

    isVisited[u] = True

    if mincost == 2000:
      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(d)

prim_mst(n)

Submission status: Wrong Answer

Solution code:
n=int(input())
# m=[list(map(int,input().split()))for _ in[0]*n]
m = [[-1 for i in range(n)] for j in range(n)]
d=[0]+[10**9]*n
b=[1]*n
a=0
while 1:
  u=-1
  for i in range(n):
    if b[i] and (u<0 or d[i]<d[u]):
      u=i
  if u<0:
    break
  b[u]=0
  a+=d[u]
  for v in range(n):
    t=m[u][v]
    if t+1 and d[v]>t:
      d[v]=t
print(a)

Submission status: Wrong Answer

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

d=[0]+[10**9]*n
visited=[0]*n
while 1:
  u=-1
  for i in range(n):
    if not visited[i] and (u<0 or d[i]<d[u]):
      u = i
  if u < 0:
    break
  visited[u]=1
  for v in range(n):
    t = m[u][v]
    if t + 1 and d[v] > t:
      d[v] = t
print(sum(d))

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
class Forest:
    def __init__(self, g, id):
        self.forest = set([id])
        self.graph = g
        self.next_wait = self.graph[id]
        self.wait = 0
    def add_tree(self, id):
        self.wait += self.next_wait[id]
        self.forest.update([id])
        
        self.marge_next_wait(id)
    def next_tree(self):
        min_id = min_wait = None
        for id, wait in self.next_wait.items():
            if id not in self.forest:
                if min_wait == None or min_wait > wait:
                    min_wait = wait
                    min_id = id
        return min_id
    def marge_next_wait(self, merge_id):
        for id, wait in self.graph[merge_id].items():
            if id not in self.next_wait or self.next_wait[id] > wait:
                self.next_wait[id] = wait
n = int(input())
g = [{e:i for e, i in enumerate(map(int, input().split())) if i != -1} for _ in range(n)]
forest = Forest(g,0)
for i in range(4):
    id = forest.next_tree()
    forest.add_tree(id)
print(forest.wait)

Submission status: Wrong Answer

Solution code:
INFTY = 10000000000000000000000000000
n = int(raw_input())
A = {}
for i in range(n):
    A[i] = {}
    for j,c in enumerate(raw_input().strip().split(' ')):
        c = int(c)
        if c > 0: A[i][j] = c

d = {}
chosen = {}
for i in range(n):
    d[i] = INFTY
    chosen[i] = False
d[0] = 0

ans = 0
while True:
    mincost = INFTY
    u = -1
    for i in range(n):
        if (not chosen[i]) and mincost > d[i]:
            mincost = d[i]
            u = i
    if mincost == INFTY: break
    ans += mincost
    chosen[u] = True
    for i in range(n):
        if not chosen[i] and i in A[u] and A[u][i] < d[i]:
            d[i] = A[u][i]


print ans

Submission status: Wrong Answer

Solution code:
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

Submission status: Wrong Answer

Solution code:
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())
amin = 2001
next = 0
for i in xrange(n):
	if 0 < a[0][i] < amin:
		amin = a[0][i]
		addA = i
A.append(addA)
NY.remove(addA)
long = amin
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: Wrong Answer

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

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

Submission status: Wrong Answer

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


n=int(raw_input())
A=[0]*n
for u in range(n):
    A[u]=map(int, raw_input().split())
 
result=prim(A)
print(result)

Submission status: Wrong Answer

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


n = int(raw_input())
A = [0] * n
for u in range(n):
    A[u] = map(int, raw_input().split())
 
result = prim(A)
print(result)

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

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

Submission status: Wrong Answer

Solution code:
n = input()
white = 0
gray = 1
black = 2
m = [[9999999 for i in xrange(n)] for j in xrange(n)]
d = [9999999 for i in xrange(n)]
p = [-1 for i in xrange(n)] 
color = [0 for i in xrange(n)] 

def prim():
    d[0] = 0

    while 1:
        minv = 9999999
        for i in xrange(n):
            if minv > d[i] and color[i] != black:
                u = i
                minv = d[i]
        if minv == 9999999:
            break
        color[u] = black
        for v in xrange(n):
            if color[v] != black and m[u][v] != 9999999 and m[u][v] < d[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):
    s = map(int,raw_input().split())
    for j in xrange(n):
        if m[j] != -1:
            m[i][j] = s[j] 
print prim()

Submission status: Wrong Answer

Solution code:
def kruskal(n):
    cost = []
    t = set()
    while edge:
        cmin = min(weight)
        index = weight.index(cmin)
        e = edge[index]
        del weight[index]
        del edge[index]
        if not e <= t:
            cost.append(cmin)
            t |= e
    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))

Submission status: Wrong Answer

Solution code:
import sys

def prim(E):
    V = [0]
    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)
        E[mini][minj], E[minj][mini] = -1, -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)

Submission status: Wrong Answer

Solution code:
import sys

def debug(x, table):
    for name, val in table.items():
        if x is val:
            print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
            return None

def solve():
    n = int(input())
    edges = []

    for i in range(n):
        line = [int(j) for j in input().split()]
        edges += [e for e in line[i + 1:] if e >= 0]

    edges.sort()
    ans = sum(edges[:n - 1])

    print(ans)

if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
MAX = 2001


def prim(tree: [int], adjacent_list: [[int]]):
    cost = 0
    next = 0
    for l in adjacent_list:
        l[next] = MAX
    while True:
        tree.append(next)
        min_list = list()
        for t in tree:
            min_list.append(min([(v, i) for i, v in enumerate(adjacent_list[t])]))
        min_cost, i = min(min_list)
        if min_cost == MAX:
            return cost
        cost += min_cost
        for l in adjacent_list:
            l[i] = MAX
        print(adjacent_list)
        next = i


if __name__ == '__main__':
    N = int(input())
    adjacent_list = [[int(e) if int(e) != -1 else MAX for e in input().rstrip().split()] for _ in range(N)]
    test_list = []
    print(prim(test_list, adjacent_list))
    print(test_list)

Submission status: Wrong Answer

Solution code:
MAX = 2001


def prim(tree: [int], adjacent_list: [[int]]):
    cost = 0
    next = 0
    for l in adjacent_list:
        l[next] = MAX
    while True:
        tree.append(next)
        min_list = list()
        for t in tree:
            min_list.append(min([(v, i) for i, v in enumerate(adjacent_list[t])]))
        min_cost, i = min(min_list)
        if min_cost == MAX:
            return cost
        cost += min_cost
        for l in adjacent_list:
            l[i] = MAX
        print(adjacent_list)
        next = i


if __name__ == '__main__':
    N = int(input())
    adjacent_list = [[int(e) if int(e) != -1 else MAX for e in input().rstrip().split()] for _ in range(N)]
    test_list = []
    print(prim(test_list, adjacent_list))

Submission status: Wrong Answer

Solution code:
INF = 9999


def prim(G):
    n = len(G)
    color = ['White' for _ in range(n)]
    d = [INF for _ in range(n)]
    p = [-1 for _ in range(n)]
    d[0] = 0

    while True:
        mincost = INF
        u = -1
        for i in range(n):
            if color[i] != 'Black' and d[i] < mincost:
                mincost = d[i]
                u = i

        if u == -1:
            break

        color[u] = 'Black'

        for v in range(n):
            if color[v] != 'Black' and G[u][v] != INF:
                if G[u][v] < d[v]:
                    d[v] = G[u][v]
                    p[v] = u
                    color[u] = 'Gray'

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


if __name__ == '__main__':
    n = int(input())
    GL = [list(map(int, input().split())) for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if GL[i][j] == -1:
                GL[i][j] = INF
    print(prim(GL))

Submission status: Wrong Answer

Solution code:
n = int(input())
A = [[int(i) for i in input().strip().split(" ")] for j in range(n)]

dp1={}

for i in range(n):
    for j in range(n):
        if A[i][j] != -1 :
            dp1[(i,j)] = A[i][j]
key = []
value = []
for i,j in sorted(dp1.items(), key=lambda x:x[1]):
    key.append(i)
    value.append(j)

c_v = []
N = len(key)
len_c_v = 0
ans = 0
itr = 0
while itr != N:
    if len_c_v == n:
        break
    i = key[itr][0]
    j = key[itr][1]
    if (i in c_v) == False and (j in c_v) == False:
        c_v.append(i)
        c_v.append(j)
        ans += value[itr]
        len_c_v += 2
        itr += 1
    elif (i in c_v) == False:
        c_v.append(i)
        ans += value[itr]
        itr += 1
        len_c_v += 1
    elif (j in c_v) == False:
        c_v.append(j)
        ans += value[itr]
        itr += 1
        len_c_v += 1
    else:
        itr += 1


if len_c_v != n:
    print(-1)
else:
    print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
A = [[int(i) for i in input().strip().split(" ")] for j in range(n)]

dp1={}

for i in range(n):
    for j in range(n):
        if A[i][j] != -1 :
            dp1[(i,j)] = A[i][j]
key = []
value = []
for i,j in sorted(dp1.items(), key=lambda x:x[1]):
    key.append(i)
    value.append(j)

c_v = []
N = len(key)
len_c_v = 0
ans = 0
itr = 0
while itr != N:
    if len_c_v == n:
        break
    i = key[itr][0]
    j = key[itr][1]
    if (i in c_v) == False and (j in c_v) == False:
        c_v.append(i)
        c_v.append(j)
        ans += value[itr]
        len_c_v += 2
        itr += 1
    elif (i in c_v) == False:
        c_v.append(i)
        ans += value[itr]
        itr += 1
        len_c_v += 1
    elif (j in c_v) == False:
        c_v.append(j)
        ans += value[itr]
        itr += 1
        len_c_v += 1
    else:
        itr += 1


if len_c_v != n:
    print(-1)
else:
    print(str(ans))

Submission status: Wrong Answer

Solution code:
import sys
from operator import add

n = int(sys.stdin.readline().strip())
A = [ [0] for i in range(n)]
for i in range(n):
	temp = map(int ,sys.stdin.readline().strip().split(" "))
	A[i] = temp


weight = [None for i in range(n)]
mitayatu=[False for i in range(n)]

def min(array):
	temp = 100000
	index= 0
	for i in range(n):
		if array[i] is not None and mitayatu[i]==False:
			if temp>array[i]:
				temp == array[i]
				index = i
	return index

def owari():
	for i in mitayatu:
		if i is False:
			return False
	return True
# zero origin
def prim(nodeid):
	if owari() == True:
		return
	if mitayatu[nodeid]==True:
		return
	mitayatu[nodeid]=True
	for i in range(n):
		if A[nodeid][i]!=-1:
			if weight[i] is None:
				weight[i]=A[nodeid][i]
			elif weight[i]>A[nodeid][i]:
				weight[i]=A[nodeid][i]
	prim(min(weight))

weight[0]=0
prim(0)


print reduce(add, weight)

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop

def prim(G):
    n = len(G)
    heap = []
    s = 0
    for v, c in G[s].items():
        heappush(heap, (c, v))
    added = set()
    added.add(s)
    cost = 0
    while len(added) < n:
        cu, u = heappop(heap)
        added.add(u)
        cost += cu
        for v, c in G[u].items():
            if v in added:
                continue
            heappush(heap, (c, v))
    return cost

n = int(raw_input())
G = {}
for i in range(n):
    if i not in G:
        G[i] = {}
    row = map(int, raw_input().strip().split(' '))
    for j in range(n):
        if row[j] == -1:
            continue
        G[i][j] = row[j]
        if j not in G:
            G[j] = {}
        G[j][i] = row[j]


cost = prim(G)
print cost

Submission status: Wrong Answer

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()
v.add(0)

while len(v) < n:
    print(v)
    min_w   = 10000
    min_idx = 0
    i = 0
    for node in v:
        if min_w > min(a[node]):
            min_w = min(a[node])
            i = node
            min_idx = a[i].index(min_w)
    if min_idx in v:
        a[i][min_idx] = 10000
        continue
    else:
        w += min_w
        v.add(min_idx)

print(w)

Submission status: Wrong Answer

Solution code:
n = int(input())
edgeList = []
rootList = [-1 for i in range(n)]

def getRoot(x):
    r = rootList[x]
    if r < 0:
        rootList[x] = x
    elif r != x:
        rootList[x] = getRoot(r)
    return rootList[x]
        
for i in range(n):
    a = list(map(int, input().split()))
    for j in range(i):
        if a[j] != -1:
            edgeList.append([a[j], getRoot(i), getRoot(j)])
sumLength = 0
edgeList.sort(key=lambda x: x[0])
for e in edgeList:
    x = e[1]
    y = e[2]
    if x != y:
        sumLength += e[0]
        rootList[x] = rootList[y] = min(x, y)
print(sumLength)

Submission status: Wrong Answer

Solution code:
n = int(input())
A = []
for i in range(n):
    line = input()
    A.append([int(x) for x in line.split()])

V = set(range(n))
Vnew = {0}  # ??¨???????°???¨?????????
weight = 0

while V != Vnew:
    T = V - Vnew
    minw = float('inf')
    for u in Vnew:
        for v in T:
            w = A[u][v]
            if w != -1:
                e = (u, v)
                minw = min(minw, w)
    Vnew.add(e[1])
    weight += minw


print(weight)

Submission status: Wrong Answer

Solution code:
INF = float("inf")
def MAIN():
    n = int(input())
    ans = [0] * n
    li = [INF] * n
    li[0] = 0
    A = {}
    for i in range(n):
        A[i] = {k:v for k, v in enumerate(map(int, input().split())) if v != -1}
    dp = [0]
    while dp:
        a = dp.pop()
        for k, v in A[a].items():
            if li[k] > li[a] + v:
                li[k] = li[a] + v
                ans[k] = v
                dp.append(k)
    print(sum(ans))
MAIN()

Submission status: Wrong Answer

Solution code:
n=int(input())
edgeList=[]
for i in range(n):
 a=list(map(int,input().split()))
 for j in range(i):
  if a[j]>0:edgeList+=[[a[j],i,j]]
rootList=[-1]*n
sumLength=0
def getRoot(x):
 r=rootList[x]
 if r<0:rootList[x]=x
 elif r!=x:rootList[x]=getRoot(r)
 return rootList[x]
edgeList.sort(key=lambda x:x[0])
for e in edgeList:
 x=getRoot(e[1])
 y=getRoot(e[2])
 if x!=y:
  sumLength+=e[0]
  rootList[x]=rootList[y]=min(x,y)
print(sumLength)

Submission status: Wrong Answer

Solution code:
n = int(input())
sides = []
ws = []
for _ in range(n):
    sides.append(list(map(int,input().split())))
for i in range(n):
    for j in range(i+1,n):
        if sides[i][j] > 0:
            ws.append([sides[i][j],i,j])
rs = [i for i in range(n)]
def root(x):
    global rs
    if rs[x] == x:
        return(x)
    else:
        return(root(rs[x]))
ws.sort()
ans = 0
while(len(ws)):
    if root(ws[0][1]) != root(ws[0][2]):
        ans += ws[0][0]
        rs[root(rs[ws[0][2]])] = root(ws[0][1])
    del(ws[0])
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
sides = []
ws = []
ss = []
for _ in range(n):
    sides.append(list(map(int,input().split())))
for i in range(n):
    for j in range(i+1,n):
        if sides[i][j] > 0:
            ws.append([sides[i][j],i,j])
rs = [(i) for i in range(n)]
def root(x):
    global rs
    if rs[x] == x:
        return(x)
    else:
        return(root(rs[x]))
ws.sort()
ans = 0
while(len(ws)):
    if root(ws[0][1]) != root(ws[0][2]):
        ans += ws[0][0]
        rs[root(rs[ws[0][2]])] = ws[0][1]
        ss.append(ws[0])
    del(ws[0])
print(ans)