ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [백준] 11286. 절대값 힙
    코테 준비/Heap 2023. 1. 10. 02:58
    import sys
    import heapq
    n=int(sys.stdin.readline())
    heap=[]
    for i in range(n):
        x=int(sys.stdin.readline())
        if x==0:
            if len(heap)==0:
                print("0")
            else:
                print(heapq.heappop(heap)[1]) #x값 출력
        else:
            heapq.heappush(heap,(abs(x),x)) #튜플 형태로 (절대값(x),x)를 저장

    이 풀이는 시간초과 때문에 통과되지 못했다...

     

    import sys
    import heapq
    n=int(sys.stdin.readline())
    plusheap=[]
    minusheap=[]
    for i in range(n):
        x=int(sys.stdin.readline())
        if x==0:
            if len(plusheap)==0 and len(minusheap)==0:
                print("0")
            elif len(plusheap)!=0 and len(minusheap)==0:
                print(heapq.heappop(plusheap))
            elif len(plusheap)==0 and len(minusheap)!=0:
                print(-1*heapq.heappop(minusheap))
            else:
                p=min(plusheap)
                m=min(minusheap)
                if p>=m:
                    print(-1*heapq.heappop(minusheap))
                else:
                    print(heapq.heappop(plusheap))
        else:
            if x>0:
                heapq.heappush(plusheap,x)
            else:
                heapq.heappush(minusheap,-x)

    '코테 준비 > Heap' 카테고리의 다른 글

    [프로그래머스] 더 맵게  (0) 2023.01.25
    [백준] 11279. 최대힙  (1) 2023.01.10
    [백준] 1972. 최소힙 (heapq 알아두기)  (0) 2023.01.10
Designed by Tistory.