๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Coding Test/Algorithms

[SWEA] 5215.ํ–„๋ฒ„๊ฑฐ ๋‹ค์ด์–ดํŠธ/Python - D3

by The Future Engineer, Lucy 2024. 11. 12.
728x90
๋ฐ˜์‘ํ˜•

โ“๋ฌธ์ œ

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWT-lPB6dHUDFAVT

 

SW Expert Academy

SW ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์—ญ๋Ÿ‰ ๊ฐ•ํ™”์— ๋„์›€์ด ๋˜๋Š” ๋‹ค์–‘ํ•œ ํ•™์Šต ์ปจํ…์ธ ๋ฅผ ํ™•์ธํ•˜์„ธ์š”!

swexpertacademy.com

์„ฑ๋Šฅ ์š”์•ฝ

๋ฉ”๋ชจ๋ฆฌ: 57,264 KB, ์‹œ๊ฐ„: 590 ms, ์ฝ”๋“œ๊ธธ์ด: 441 Bytes

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

์ •ํ•ด์ง„ ์นผ๋กœ๋ฆฌ๋ฅผ ๋„˜๊ธฐ์ง€ ์•Š์œผ๋ฉด์„œ ๊ฐ€์žฅ ์ ์ˆ˜๊ฐ€ ๋†’์€ ํ–„๋ฒ„๊ฑฐ๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค.
์ •ํ•ด์ง„ ์นผ๋กœ๋ฆฌ๊ฐ€ 1000์ผ ๋•Œ, ์ฃผ์–ด์ง„ ์žฌ๋ฃŒ๋“ค๋กœ 1000์„ ๋„˜๊ธฐ์ง€ ์•Š์œผ๋ฉด์„œ ๊ฐ€์žฅ ์ ์ˆ˜๊ฐ€ ๋†’์€ ํ–„๋ฒ„๊ฑฐ๋ฅผ ๋งŒ๋“ค์–ด์•ผ ํ•œ๋‹ค.
์ฃผ์–ด์ง„ ์žฌ๋ฃŒ๋“ค์˜ ์ ์ˆ˜์™€ ์นผ๋กœ๋ฆฌ๊ฐ€ ๊ฐ๊ฐ (100, 200), (300, 500), (250, 300), (500, 1000), (400, 400)์ด๋ผ๊ณ  ํ•œ๋‹ค๋ฉด
์ด๋•Œ ๊ฐ€์žฅ ๋†’์€ ์ ์ˆ˜๋Š” 750์ด ๋˜๋ฉฐ ์นผ๋กœ๋ฆฌ๋Š” 900์œผ๋กœ ์ •ํ•ด์ง„ ์นผ๋กœ๋ฆฌ๋ฅผ ๋„˜๊ธฐ์ง€ ์•Š๋Š”๋‹ค.
์ฒซ๋ฒˆ์งธ ์žฌ๋ฃŒ๋ถ€ํ„ฐ ์‚ดํŽด๋ณธ๋‹ค. ํ˜น์€ ๋‘๋ฒˆ์งธ ์žฌ๋ฃŒ๋ถ€ํ„ฐ ์ ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•  ์ˆ˜ ์žˆ๋‹ค. ์ฆ‰, ํ˜„์žฌ ์ ์ˆ˜์—์„œ ์ง€๊ธˆ ์œ„์น˜์˜ ์žฌ๋ฃŒ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๋‹ค์Œ ์œ„์น˜์˜ ์žฌ๋ฃŒ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด์„œ ๊ฐ€์žฅ ๋†’์€ ์ ์ˆ˜๋ฅผ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด๋‹ค.

๐Ÿ’ป์ฝ”๋“œ

t = int(input())

def dfs(s, c, d):
    global ms
    if c > l:
        return 
    ms = max(ms, s)
    if d == n:
        return

    dfs(s + scores[d], c + calories[d], d+1)
    dfs(s, c, d+1)


for i in range(1, t + 1):
    n, l = map(int, input().split())
    scores = [0] * n
    calories = [0] * n

    for j in range(n):
        scores[j], calories[j] = map(int, input().split())

    ms = 0
    dfs(0, 0, 0)


    print(f"#{i} {ms}")

๐Ÿ“ํ›„๊ธฐ

์ฒ˜์Œ์—๋Š” napsack๋ฌธ์ œ์ฒ˜๋Ÿผ dp์ธ ์ค„ ์•Œ๊ณ  ์‹œ๋„ํ–ˆ๋Š”๋ฐ ์•„๋ฌด๋ฆฌ ์ƒ๊ฐํ•ด๋„ dp๋กœ ์–ด๋–ป๊ฒŒ ํ•ด์•ผ ํ• ์ง€ ๊ฐ์ด ์•ˆ ์žกํ˜”๋‹ค. ์ „์—๋„ ๋น„์Šทํ•œ ์œ ํ˜•์˜ ๋ฌธ์ œ๋„ ์ฒ˜์Œ์—๋Š” dp์ธ๊ฐ€ ํ–ˆ๋Š”๋ฐ ๊ทธ ๋ฌธ์ œ๋„ ๊ฒฐ๊ตญ dfs ๋ฌธ์ œ์˜€๋˜ ๊ฒƒ ๊ฐ™๋‹ค. ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œ๋Š” ์™œ ํ’€์–ด๋„ํ’€์–ด๋„ ๊ฐ์ด ์•ˆ ์žกํžˆ๋Š” ๊ฒƒ ๊ฐ™์ง€..

728x90
๋ฐ˜์‘ํ˜•