본문 바로가기

알고리즘 문제풀이

Swea D3_ 이진힙 Python Tree

첫 번째 풀이

def min_heap(node):
    global last
    last += 1
    heap[last] = arr[node]
    child = last
    parent = child // 2 # 완전 이진 트리라서 가능
    if node<0:
        return
    while parent and heap[parent] > heap[child]: # 부모가 있는데 부모가 자식보다 크다면?
        heap[parent] , heap[child] = heap[child],  heap[parent] # 교환
        child = parent
        parent = child//2
def binar_sum():
    value = 0
    node = n //2 # 3 1 0
    while node:
        value += heap[node]
        node //= 2
    return value


t = int(input())
for tc in range(1,t+1):
    n = int(input())
    arr = list(map(int,input().split()))
    # print(arr)
    heap = [0] * (n+1)
    # 2 5 가 더해져야된다.
    # 트리부터 만들기
    # 마지막 인수
    last = 0
    for i in range(0,n):
        min_heap(i)
    print(heap)
    print(f'#{tc} {binar_sum()}')

다른 날 풀이

def makeHeap(node):
    global last
    # tree의 루트 인덱스를 1부터 시작하겠다.
    tree[last] = arr[node]
    child = last
    parrent = child // 2
    while parrent and tree[parrent] > tree[child]: # parrent가 0이 아니고 부모보다 자식이 작은 숫자라면?
        tree[parrent] , tree[child] = tree[child], tree[parrent]
        child = parrent
        parrent = child//2
    last += 1

def heap_sum(node):
    result = 0
    flag = 1
    child = node
    parrent = child // 2
    while parrent:
        result += tree[parrent]
        child = parrent
        parrent = child // 2
    return result

t = int(input())
for tc in range(1,t+1):
    n = int(input())
    arr = list(map(int,input().split()))
    # print()
    # 이진 최소값 구하기 => 재귀
    # 일단 tree선언
    tree = [0] * (n+1)
    last = 1 # 노드 인덱스에 들어갈 arr[last] 값
    for i in range(n):
        makeHeap(i) # 노드 번호는 루트가 1

    # print(tree)
    print(f'#{tc} {heap_sum(n)}')