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

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

 

2343๋ฒˆ: ๊ธฐํƒ€ ๋ ˆ์Šจ

๊ฐ•ํ† ๋Š” ์ž์‹ ์˜ ๊ธฐํƒ€ ๋ ˆ์Šจ ๋™์˜์ƒ์„ ๋ธ”๋ฃจ๋ ˆ์ด๋กœ ๋งŒ๋“ค์–ด ํŒ๋งคํ•˜๋ ค๊ณ  ํ•œ๋‹ค. ๋ธ”๋ฃจ๋ ˆ์ด์—๋Š” ์ด N๊ฐœ์˜ ๋ ˆ์Šจ์ด ๋“ค์–ด๊ฐ€๋Š”๋ฐ, ๋ธ”๋ฃจ๋ ˆ์ด๋ฅผ ๋…นํ™”ํ•  ๋•Œ, ๋ ˆ์Šจ์˜ ์ˆœ์„œ๊ฐ€ ๋ฐ”๋€Œ๋ฉด ์•ˆ ๋œ๋‹ค. ์ˆœ์„œ๊ฐ€ ๋’ค๋ฐ”๋€Œ๋Š” ๊ฒฝ

www.acmicpc.net


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

๐ŸŽจ Go

// https://www.acmicpc.net/problem/2343
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 lessons = make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d ", &lessons[i])
	}
	fmt.Fprintln(writer, blueray(lessons, m))
}

func blueray(lessons []int, m int) int {
	var low, high int // low: ๋ ˆ์Šจ ์ค‘ ๊ฐ€์žฅ ๊ธด ์‹œ๊ฐ„, high: ๋ ˆ์Šจ ๊ธธ์ด์˜ ์ด ํ•ฉ
	for i := 0; i < len(lessons); i++ {
		high += lessons[i]
		if low < lessons[i] {
			low = lessons[i]
		}
	}

	for low <= high {
		bluerayCount := 0
		sum := 0
		mid := (low + high) / 2 // ๋ธ”๋ฃจ๋ ˆ์ด ํฌ๊ธฐ
		for i := 0; i < len(lessons); i++ {
			if sum+lessons[i] > mid { // ๋ธ”๋ฃจ๋ ˆ์ด ํฌ๊ธฐ๋ณด๋‹ค ์ปค์ง€๋Š” ๊ฒฝ์šฐ, sum์„ 0์œผ๋กœ ์ดˆ๊ธฐํ™”, ๋ธ”๋ฃจ๋ ˆ์ด ๊ฐœ์ˆ˜ 1์ฆ๊ฐ€
				sum = 0
				bluerayCount++
			}
			sum += lessons[i]
		}
		bluerayCount++
		if bluerayCount <= m {
			high = mid - 1 // ๋ธ”๋ฃจ๋ ˆ์ด ๊ฐœ์ˆ˜๊ฐ€ m ์ดํ•˜์ธ ๊ฒฝ์šฐ, ๋ธ”๋ฃจ๋ ˆ์ด ํฌ๊ธฐ ํƒ์ƒ‰์˜ ์ตœ๋Œ€ ๋ฒ”์œ„๋ฅผ ๊ฐ์†Œ์‹œํ‚จ๋‹ค
		} else {
			low = mid + 1 // ๋ธ”๋ฃจ๋ ˆ์ด ๊ฐœ์ˆ˜๊ฐ€ m๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ, ๋ธ”๋ฃจ๋ ˆ์ด ํฌ๊ธฐ ํƒ์ƒ‰์˜ ์ตœ์†Œ ๋ฒ”์œ„๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค
		}
	}
	return low
}

๐ŸŽจ Python3

# https://www.acmicpc.net/problem/2343
import sys

def blueray(lessons, m):
    low, high = 0, 0
    for lesson in lessons:
        high += lesson
        low = max(low, lesson)

    while low <= high:
        blueray_count = 0
        sum = 0
        mid = (low+high) // 2
        for i in range(len(lessons)):
            if sum+lessons[i] > mid:
                sum = 0
                blueray_count += 1
            sum += lessons[i]
        blueray_count += 1
        if blueray_count <= m:
            high = mid-1
        else:
            low = mid+1
    return low

if __name__ == "__main__":
    n, m = list(map(int, sys.stdin.readline().split()))
    lessons = list(map(int, sys.stdin.readline().split()))
    print(blueray(lessons, m))
728x90
๋Œ“๊ธ€