dev/algorithm
BOJ / 11286๋ฒ / ์ ๋๊ฐ ํ [Go][Python3]
crscnt
2020. 11. 30. 21:00
๐ฉ๐ป๐ป ๋ฌธ์
11286๋ฒ: ์ ๋๊ฐ ํ
์ฒซ์งธ ์ค์ ์ฐ์ฐ์ ๊ฐ์ N(1≤N≤100,000)์ด ์ฃผ์ด์ง๋ค. ๋ค์ N๊ฐ์ ์ค์๋ ์ฐ์ฐ์ ๋ํ ์ ๋ณด๋ฅผ ๋ํ๋ด๋ ์ ์ x๊ฐ ์ฃผ์ด์ง๋ค. ๋ง์ฝ x๊ฐ 0์ด ์๋๋ผ๋ฉด ๋ฐฐ์ด์ x๋ผ๋ ๊ฐ์ ๋ฃ๋(์ถ๊ฐํ๋) ์ฐ์ฐ์ด๊ณ , x๊ฐ 0
www.acmicpc.net
โ๐ป ํ์ด
๐จ Go
// https://www.acmicpc.net/problem/11286
// ์๋ก์ด ๊ธฐ์ค์ผ๋ก ๋ฝ๋ ์ฐ์ ์์ ํ๋ฅผ ๋ง๋๋ ๋ฌธ์
package main
import (
"bufio"
"fmt"
"math"
"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([]int, n+1)
for i := 0; i < n; i++ {
var x int
fmt.Fscanln(reader, &x)
if x == 0 {
fmt.Fprintln(writer, heap.deleteHeap())
} else {
heap.insertHeap(x)
}
}
}
type Heap struct {
heapArr []int
numOfData int
}
func (heap *Heap) deleteHeap() (delVal int) {
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 math.Abs(float64(lastVal)) < math.Abs(float64(heap.heapArr[childIdx])) ||
math.Abs(float64(lastVal)) == math.Abs(float64(heap.heapArr[childIdx])) && 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 math.Abs(float64(heap.heapArr[parentIdx*2])) > math.Abs(float64(heap.heapArr[parentIdx*2+1])) {
return parentIdx*2 + 1
} else if math.Abs(float64(heap.heapArr[parentIdx*2])) == math.Abs(float64(heap.heapArr[parentIdx*2+1])) {
if heap.heapArr[parentIdx*2] >= heap.heapArr[parentIdx*2+1] {
return parentIdx*2 + 1
}
}
return parentIdx * 2
}
}
func (heap *Heap) insertHeap(x int) {
heap.numOfData++
var idx = heap.numOfData
for idx != 1 {
if math.Abs(float64(x)) < math.Abs(float64(heap.heapArr[idx/2])) ||
math.Abs(float64(x)) == math.Abs(float64(heap.heapArr[idx/2])) && 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/11286
# ์๋ก์ด ๊ธฐ์ค์ผ๋ก ๋ฝ๋ ์ฐ์ ์์ ํ๋ฅผ ๋ง๋๋ ๋ฌธ์
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(heapq.heappop(h)[1])
else:
print(0)
else:
heapq.heappush(h, (abs(x), x)) # ํํ ํ์ฉ
728x90