dev/algorithm
BOJ / 2805번 / 나무 자르기 [Go][Python3]
crscnt
2020. 11. 21. 21:00
👩🏻💻 문제
2805번: 나무 자르기
첫째 줄에 나무의 수 N과 상근이가 집으로 가져가려고 하는 나무의 길이 M이 주어진다. (1 ≤ N ≤ 1,000,000, 1 ≤ M ≤ 2,000,000,000) 둘째 줄에는 나무의 높이가 주어진다. 나무의 높이의 합은 항상 M을
www.acmicpc.net
✍🏻 풀이
🎨 Go
// https://www.acmicpc.net/problem/2805
// 이분 탐색을 응용하여 최솟값이나 최댓값을 찾는 문제 2
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
writer := bufio.NewWriter(os.Stdout)
defer writer.Flush()
var n, m int
fmt.Fscanln(reader, &n, &m)
var trees = make([]int, n)
var maxTree int
for i := 0; i < n; i++ {
fmt.Fscanf(reader, "%d ", &trees[i])
if maxTree < trees[i] {
maxTree = trees[i]
}
}
fmt.Fprintln(writer, getMaxHeight(m, maxTree, trees))
}
func getMaxHeight(m, maxTree int, trees []int) (maxHeight int) {
start := 1
end := maxTree // 탐색 범위 설정
var mid int
for start <= end {
mid = (start + end) / 2 // 이분 탐색과 유사한 방식으로 범위를 좁혀 나간다.
totalHeight := 0
for i := 0; i < len(trees); i++ {
if trees[i] > mid {
totalHeight += (trees[i] - mid)
}
}
if totalHeight >= m {
if maxHeight < mid {
maxHeight = mid
start = mid + 1
}
} else {
end = mid - 1
}
}
return
}
🎨 Python3
# https://www.acmicpc.net/problem/2805
# 이분 탐색을 응용하여 최솟값이나 최댓값을 찾는 문제 2
import sys
def get_max_height(m, max_tree, trees):
start, end, mid, max_height = 1, max_tree, 0, 0
while start <= end:
mid = (start + end) // 2
total_height = 0
for i in range(len(trees)):
if trees[i] > mid:
total_height += (trees[i] - mid)
if total_height >= m:
if max_height < mid:
max_height = mid
start = mid + 1
else:
end = mid - 1
return max_height
if __name__ == "__main__":
n, m = map(int, sys.stdin.readline().split())
trees = list(map(int, sys.stdin.readline().split()))
print(get_max_height(m, max(trees), trees))
728x90