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

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

 

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
๋Œ“๊ธ€