DevYoon

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์–‘๊ถ๋Œ€ํšŒ (Python) ๋ณธ๋ฌธ

PS/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์–‘๊ถ๋Œ€ํšŒ (Python)

gimewn 2022. 11. 2. 01:08

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

 

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

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

programmers.co.kr

 

๐Ÿ’ฌ ๋ผ์ด์–ธ์ด ํ™”์‚ด์„ ์  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ๋ฅผ DFS๋กœ ๊ตฌํ•œ ํ›„, ๋ผ์ด์–ธ๊ณผ ์–ดํ”ผ์น˜์˜ ์ ์ˆ˜์ฐจ๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค.

๐Ÿ’ฌ ํ’€๋‹ค๊ฐ€ ๋ง‰ํ˜€์„œ ๊ณ ๋ฏผํ•˜๋‹ค ์นด์นด์˜ค์˜ ํ•ด์„ค์„ ์ฐธ๊ณ ํ–ˆ๊ณ , ๋ผ์ด์–ธ์ด ํ•œ ๊ณผ๋…์— ์ด๋ณผ ์ˆ˜ ์žˆ๋Š” ํ™”์‚ด์˜ ์ œํ•œ์„ (0 ~ ์–ดํ”ผ์น˜๊ฐ€ ์œ ํ™”์‚ด +1)๋กœ ๋‘์–ด์•ผ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚˜์ง€ ์•Š๋Š”๋‹ค๋Š” ํ•œ๋‹ค๋Š” ํŒ์„ ์–ป์—ˆ๋‹ค.

๐Ÿ’ฌ ์ค‘๊ฐ„์— ๊ณ„์† answer์˜ ๊ฐ’์ด 0์œผ๋กœ ๊ฐ€๋“์ฐจ ๋‚˜์˜ค๋Š” ์˜ค๋ฅ˜๊ฐ€ ์žˆ์—ˆ๋‹ค...๐Ÿ˜ญ ๊ณ„์† ๋””๋ฒ„๊น… ํ•ด๋ด๋„ ์ด์œ ๋ฅผ ๋ชจ๋ฅด๊ฒ ์–ด์„œ ๊ตฌ๊ธ€๋ง ํ•ด๋ณด์•˜๋Š”๋ฐ list(๋ฐฐ์—ด) ์ด ๋ฐฉ์‹์œผ๋กœ ํ•ด๊ฒฐํ•˜์‹  ๋ถ„์ด ์žˆ์—ˆ๋‹ค. ์™œ ์ €๋ ‡๊ฒŒ ํ•˜๋ฉด ๋˜๋Š” ๊ฑฐ์ง€,,,ใ… ใ…œ

โžก ์ด์œ ๋ฅผ ์•Œ์•˜๋‹ค! ์›๋ž˜๋Š” max_list = lion์œผ๋กœ ๋„ฃ์—ˆ๋Š”๋ฐ, lion ๋ฐฐ์—ด์€ DFS ํ•จ์ˆ˜์—์„œ ์ถ”ํ›„ [0, 0, 0, 0, ...] ์œผ๋กœ ์ดˆ๊ธฐํ™” ๋œ๋‹ค. ๊ทธ๋ž˜์„œ ํ˜น์‹œ ์–•์€ ๋ณต์‚ฌ ๋ฌธ์ œ์ผ๊นŒ ์‹ถ์–ด deepcopy๋ฅผ ์จ์ฃผ์—ˆ๋Š”๋ฐ, ํ•ด๊ฒฐ๋˜์—ˆ๋‹ค!๐Ÿค—

 

from copy import deepcopy

max_gap = 0
max_list = []

def cal_score(apeach, lion):
    global max_gap, max_list
    apeach_score = 0
    lion_score = 0
    for idx in range(11):
        if apeach[idx] == 0 and lion[idx] == 0:
            continue
        if apeach[idx] >= lion[idx]:
            apeach_score += 10-idx
        elif apeach[idx] < lion[idx]:
            lion_score += 10-idx

    if lion_score > apeach_score:
        gap = lion_score - apeach_score
        if gap > max_gap:
            max_gap = gap
            max_list = deepcopy(lion)

        elif gap == max_gap:
            for idx in range(10, -1, -1):
                if lion[idx] > max_list[idx]:
                    max_list = deepcopy(lion)
                    break
                elif lion[idx] < max_list[idx]:
                    break

def DFS(idx, lion, shot, apeach):
    if shot == 0:
        cal_score(apeach, lion)
        return
    if idx == 11:
        return
    a_score = apeach[idx]
    for num in range(a_score+2):
        if shot >= num:
            lion[idx] = num
            DFS(idx+1, lion, shot-num, apeach)
            lion[idx] = 0

def solution(n, info):
    global max_list
    temp = [0 for _ in range(11)]
    DFS(0, temp, n, info)

    if max_list:
        return max_list
    else:
        return [-1]