import heapq



n = int(eval(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)
import heapq



n = int(eval(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)
import heapq

n = int(eval(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)

import heapq

n = int(eval(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)

-    queue.extend(edges[vertex]) -    heapq.heapify(queue) +    for t in edges[vertex]: +        if not visited[t[1]]: +            heapq.heappush(queue, t)