ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป ๋ฌธ์ œ

 

1927๋ฒˆ: ์ตœ์†Œ ํž™

์ฒซ์งธ ์ค„์— ์—ฐ์‚ฐ์˜ ๊ฐœ์ˆ˜ N(1≤N≤100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” ์—ฐ์‚ฐ์— ๋Œ€ํ•œ ์ •๋ณด๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์ •์ˆ˜ x๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋งŒ์•ฝ x๊ฐ€ ์ž์—ฐ์ˆ˜๋ผ๋ฉด ๋ฐฐ์—ด์— x๋ผ๋Š” ๊ฐ’์„ ๋„ฃ๋Š”(์ถ”๊ฐ€ํ•˜๋Š”) ์—ฐ์‚ฐ์ด๊ณ , x๊ฐ€ 0์ด

www.acmicpc.net


โœ๐Ÿป ํ’€์ด

๐ŸŽจ Go

// https://www.acmicpc.net/problem/1927
// ์ตœ์†Ÿ๊ฐ’์„ ๋น ๋ฅด๊ฒŒ ๋ฝ‘๋Š” ๋ฌธ์ œ
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n int
	fmt.Fscanln(reader, &n)

	var heap Heap
	heap.heapArr = make([]uint, n+1)

	for i := 0; i < n; i++ {
		var x uint
		fmt.Fscanln(reader, &x)
		if x == 0 {
			fmt.Fprintln(writer, heap.deleteHeap())
		} else {
			heap.insertHeap(x)
		}
	}
}

type Heap struct {
	heapArr   []uint
	numOfData int
}

func (heap *Heap) deleteHeap() (delVal uint) {
	if heap.numOfData == 0 {
		return
	}
	delVal = heap.heapArr[1]
	lastVal := heap.heapArr[heap.numOfData]
	var parentIdx = 1
	var childIdx = heap.getPriorityChildIdx(parentIdx)
	for childIdx != -1 {
		if lastVal < heap.heapArr[childIdx] {
			break
		}
		heap.heapArr[parentIdx] = heap.heapArr[childIdx]
		parentIdx = childIdx
		childIdx = heap.getPriorityChildIdx(parentIdx)
	}
	heap.heapArr[parentIdx] = lastVal
	heap.numOfData--
	return
}

func (heap *Heap) getPriorityChildIdx(parentIdx int) int {
	if parentIdx*2 > heap.numOfData {
		return -1
	} else if parentIdx*2 == heap.numOfData {
		return parentIdx * 2
	} else {
		if heap.heapArr[parentIdx*2] > heap.heapArr[parentIdx*2+1] {
			return parentIdx*2 + 1
		}
		return parentIdx * 2
	}
}

func (heap *Heap) insertHeap(x uint) {
	heap.numOfData++
	var idx = heap.numOfData

	for idx != 1 {
		if x < heap.heapArr[idx/2] {
			heap.heapArr[idx] = heap.heapArr[idx/2]
			idx = idx / 2
		} else {
			break
		}
	}
	heap.heapArr[idx] = x
}

๐ŸŽจ Python3

# https://www.acmicpc.net/problem/1927
# ์ตœ์†Ÿ๊ฐ’์„ ๋น ๋ฅด๊ฒŒ ๋ฝ‘๋Š” ๋ฌธ์ œ
import sys, heapq

if __name__ == "__main__":
    n = int(sys.stdin.readline())
    h = []

    for i in range(n):
        x = int(sys.stdin.readline())
        if x == 0:
            if len(h) == 0:
                print(0)
            else:
                print(heapq.heappop(h))
        else:
            heapq.heappush(h, x)
728x90
๋Œ“๊ธ€