DevYoon

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ ๊ณต๋ถ€ (Python) ๋ณธ๋ฌธ

PS/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ ๊ณต๋ถ€ (Python)

gimewn 2022. 10. 29. 23:27

link ๐Ÿ”— https://school.programmers.co.kr/learn/courses/30/lessons/118668

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๐Ÿ’ญ ์ฒ˜์Œ์— BFS๋กœ ์‹œ๋„ํ–ˆ์œผ๋‚˜, ๋‹ต์ด ์ž˜ ๋‚˜์˜ค์ง€ ์•Š์•˜๋‹ค.

๐Ÿ’ญ ๊ณ ๋ฏผํ•˜๋‹ค๊ฐ€ ์นด์นด์˜ค์˜ ํ•ด์„ค์„ ์ฐธ๊ณ ํ–ˆ๊ณ , DP๋กœ ํ’€์–ด์•ผ ์ •ํ™•์„ฑ๊ณผ ํšจ์œจ์„ฑ ๋ชจ๋‘ ํ†ต๊ณผํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ž„์„ ์•Œ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

๐Ÿ’ญ ๋ฌธ์ œ๋ฅผ ํ’€๋ฉด์„œ ๊ฐ€์žฅ ํ—ท๊ฐˆ๋ ธ๋˜ ๋ถ€๋ถ„์€, ์ตœ๋Œ€ ์•Œ๊ณ ๋ ฅ๊ณผ ์ฝ”๋”ฉ๋ ฅ์„ ๋„˜์–ด์„œ๋Š” ์•ˆ ๋œ๋‹ค๋Š” ๊ฒƒ! ์ด ๋ถ€๋ถ„์„ ์œ ์˜ํ•˜์ง€ ๋ชปํ•ด ์‹œ๊ฐ„์„ ์ข€ ํ—ˆ๋น„ํ–ˆ๋‹ค.

๐Ÿ’ญ DP ๋ฐฐ์—ด์„ 2์ฐจ์›์œผ๋กœ ์ƒ์„ฑํ•˜๊ณ , ๊ฐ ์•Œ๊ณ ๋ ฅ๊ณผ ์ฝ”๋”ฉ๋ ฅ ์กฐํ•ฉ์„ ๋‹ฌ์„ฑํ•˜๋Š” ๋ฐ์— ๋“œ๋Š” ์ตœ๋‹จ ์‹œ๊ฐ„์„ ๊ธฐ๋กํ•ด์ฃผ๋Š” ๊ฒŒ ํ•ต์‹ฌ์ด์—ˆ๋˜ ๊ฒƒ ๊ฐ™๋‹ค.

 

def solution(alp, cop, problems):
    # alp_req, cop_req, alp_rwd, cop_rwd, cost
    answer = 0
    max_alp = 0
    max_cop = 0
    # ๋ชจ๋“  ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•œ ์ตœ๋Œ€ ์•Œ๊ณ ๋ ฅ๊ณผ ์ฝ”๋”ฉ๋ ฅ
    for pb in problems:
        max_alp = max(pb[0], max_alp)
        max_cop = max(pb[1], max_cop)

    # ์ตœ๋Œ€ ์•Œ๊ณ ๋ ฅ๊ณผ ์ฝ”๋”ฉ๋ ฅ์„ ๋„˜์–ด๊ฐ€๋ฉด ์•ˆ ๋จ
    alp = min(alp, max_alp)
    cop = min(cop, max_cop)

    # dp ๋ฐฐ์—ด ์ƒ์„ฑ
    dp = [[float('inf')]*(max_cop+1) for _ in range(max_alp+1)]

    # ํ˜„์žฌ ์•Œ๊ณ ๋ ฅ๊ณผ ์ฝ”๋”ฉ๋ ฅ => ์‹œ๊ฐ„ 0์œผ๋กœ ์ดˆ๊ธฐํ™”
    dp[alp][cop] = 0

    for y in range(alp, max_alp+1):
        for x in range(cop, max_cop+1):
            if y < max_alp:
                # ์•Œ๊ณ ๋ ฅ 1์„ ์˜ฌ๋ฆฌ๊ธฐ ์œ„ํ•ด 1์‹œ๊ฐ„ ๊ณต๋ถ€
                dp[y+1][x] = min(dp[y+1][x], dp[y][x]+1)
            if x < max_cop:
                # ์ฝ”๋”ฉ๋ ฅ 1์„ ์˜ฌ๋ฆฌ๊ธฐ ์œ„ํ•ด 1์‹œ๊ฐ„ ๊ณต๋ถ€
                dp[y][x+1] = min(dp[y][x+1], dp[y][x]+1)
            # ๋ฌธ์ œ ํ•˜๋‚˜๋ฅผ ์„ ํƒํ•˜์—ฌ ์•Œ๊ณ ๋ ฅ๊ณผ ์ฝ”๋”ฉ๋ ฅ์„ ๋†’์ž„
            for alp_req, cop_req, alp_rwd, cop_rwd, cost in problems:
                if y >= alp_req and x >= cop_req:
                    # ์ตœ๋Œ€ ์•Œ๊ณ ๋ ฅ๊ณผ ์ตœ๋Œ€ ์ฝ”๋”ฉ๋ ฅ์„ ๋„˜์ง€ ์•Š์•„์•ผ ํ•จ
                    new_alp = min(y+alp_rwd, max_alp)
                    new_cop = min(x+cop_rwd, max_cop)
                    dp[new_alp][new_cop] = min(dp[new_alp][new_cop], dp[y][x]+cost)

    return dp[max_alp][max_cop]