ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [๋ฐฑ์ค€] 2343 ๊ธฐํƒ€ ๋ ˆ์Šจ with Python
    PS 2021. 10. 19. 21:52
    728x90
    ๋ฐ˜์‘ํ˜•

    ๐Ÿ“Œ BOJ 2343 ๊ธฐํƒ€ ๋ ˆ์Šจ

    ๐Ÿ’ก ์กฐ๊ฑด

    1. ๊ฐ•์˜์˜ ์ˆ˜ N (1 โ‰ค N โ‰ค 100,000)
      ๋ธ”๋ฃจ๋ ˆ์ด์˜ ์ˆ˜ M (1 โ‰ค M โ‰ค N)
    2. ๋ธ”๋ฃจ๋ ˆ์ด๋ฅผ ๋…นํ™”ํ•  ๋•Œ, ๊ฐ•์˜์˜ ์ˆœ์„œ๊ฐ€ ๋ฐ”๋€Œ๋ฉด ์•ˆ ๋œ๋‹ค.
    3. ๊ฐ ๊ฐ•์˜์˜ ๊ธธ์ด๊ฐ€ ๋ถ„ ๋‹จ์œ„(์ž์—ฐ์ˆ˜)๋กœ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ€๋Šฅํ•œ ๋ธ”๋ฃจ๋ ˆ์ด์˜ ํฌ๊ธฐ ์ค‘ ์ตœ์†Œ๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ.
    4. ์ด๋ถ„ํƒ์ƒ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์œ ํ˜•์˜ ๋ฌธ์ œ

    ๐Ÿ–ฅ ์†Œ์Šค ์ฝ”๋“œ

    from sys import stdin
    
    n, m = map(int, stdin.readline().split())
    arr = list(map(int, stdin.readline().split()))
    
    
    def get_cnt():
        count = 0
        temp = 0
        for i in range(n):
            if temp + arr[i] > mid:
                count += 1
                temp = 0
            temp += arr[i]
    
        if temp:
            count += 1
    
        return count
    
    
    left, right = max(arr), sum(arr)
    while left <= right:
        mid = (left + right) // 2
        cnt = get_cnt()
        if cnt > m:
            left = mid + 1
        elif cnt <= m:
            right = mid - 1
    
    print(max(left, right, mid))

    ๐Ÿ”– ์˜ˆ์ œ ๋ฐ ์‹คํ–‰๊ฒฐ๊ณผ

    ์˜ˆ์ œ

    9 3
    1 2 3 4 5 6 7 8 9

    ์‹คํ–‰๊ฒฐ๊ณผ

    17

    โŒจ๏ธ ๋ฌธ์ œ ํ’€์ด

    1. ์ด๋ถ„ํƒ์ƒ‰์„ ์œ„ํ•ด left, right, mid ๋ณ€์ˆ˜๋ฅผ ์ดˆ๊ธฐํ™” ํ•ด์ค๋‹ˆ๋‹ค.
      • left๋Š” ์ž…๋ ฅ๋ฐ›์€ ๊ฐ•์˜ ์‹œ๊ฐ„ ๋ฐฐ์—ด์˜ ๊ฐ€์žฅ ํฐ ๊ฐ’
      • right๋Š” ์ž…๋ ฅ๋ฐ›์€ ๊ฐ•์˜ ์‹œ๊ฐ„ ๋ฐฐ์—ด์˜ ํ•ฉ
      • mid = (left + right) // 2
    1. ๋ธ”๋ฃจ๋ ˆ์ด์˜ ํฌ๊ธฐ์— ๋ช‡๊ฐœ์˜ ๊ฐ•์˜๊ฐ€ ๋“ค์–ด๊ฐ€๋Š”์ง€ ๊ฒ€์‚ฌํ•˜์—ฌ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์ค๋‹ˆ๋‹ค.
      ์—ฌ๊ธฐ์„œ ๋ธ”๋ฃจ๋ ˆ์ด์˜ ํฌ๊ธฐ๋Š” mid๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๊ฒ€์‚ฌ๋ฅผ ํ•ด์ค€๋‹ค.

      def get_cnt():
       count = 0
       temp = 0
       for i in range(n):
           if temp + arr[i] > mid:
               count += 1
               temp = 0
           temp += arr[i]
      
       if temp:
           count += 1
      
       return count
    1. left๋ณ€์ˆ˜๊ฐ€ right ๋ณ€์ˆ˜๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™์„ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•˜์—ฌ ์ง„ํ–‰ํ•œ ๋’ค, left, right, mid ์ค‘ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค.
      ๋ธ”๋ฃจ๋ ˆ์ด์˜ ํฌ๊ธฐ๊ฐ€ ๋ชจ๋‘ ๊ฐ™์•„์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ตœ๋Œ“๊ฐ’์„ ์ถœ๋ ฅํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

    ๐Ÿ’พ ๋Š๋‚€์ 

    1. ์ด๋ถ„ํƒ์ƒ‰์„ ํ†ตํ•ด์„œ ํ’€์–ด๋‚ด๋Š” ๋ฌธ์ œ์˜€๋‹ค.
    2. ๋ฌธ์ œ๋ฅผ ์ดํ•ดํ•˜์ง€ ๋ชปํ•ด์„œ ์กฐ๊ธˆ ํ—ค๋งธ๋˜ ๋ฌธ์ œ์˜€๋‹ค.
    3. get_cnt ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•˜๋ ค๋‹ค๊ฐ€ ์ˆœ์„œ๊ฐ€ ๋ฐ”๋€Œ๋ฉด ์•ˆ๋œ๋‹ค๋Š” ์กฐ๊ฑด์„ ๋ณด๊ณ  ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค.
    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€

Designed by Tistory.