DevYoon

[SWEA] 4008. ์ˆซ์ž ๋งŒ๋“ค๊ธฐ (Python) ๋ณธ๋ฌธ

PS/SWEA

[SWEA] 4008. ์ˆซ์ž ๋งŒ๋“ค๊ธฐ (Python)

gimewn 2022. 4. 6. 00:02

link ๐Ÿ”— https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWIeRZV6kBUDFAVH

 

SW Expert Academy

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

swexpertacademy.com

 

1๏ธโƒฃ DFS๋กœ ๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ์—ฐ์‚ฐ์ž ์กฐํ•ฉ ๊ตฌํ•ด์ฃผ๊ธฐ

2๏ธโƒฃ calculate() ํ•จ์ˆ˜๋กœ ์ˆซ์ž+์—ฐ์‚ฐ์ž, ์™ผ์ชฝ → ์˜ค๋ฅธ์ชฝ ์ˆœ์„œ๋กœ ๊ณ„์‚ฐ

3๏ธโƒฃ Max, Min๊ณผ ๋น„๊ตํ•˜์—ฌ ๊ฐฑ์‹ 

 

t = int(input())
 
def calculate(operator):
    global Max, Min
    temp = num[0]
    for i in range(1, N):
        if operator[i-1] == '+':
            temp += num[i]
        elif operator[i-1] == '-':
            temp -= num[i]
        elif operator[i-1] == '*':
            temp *= num[i]
        else:
            temp /= num[i]
            temp = int(temp)
    if Max < temp:
        Max = temp
    if Min > temp:
        Min = temp
 
def dfs(level, operator):
    global cal
    if level == limit:
        calculate(operator)
        return
    for i in range(4):
        if cal[i] > 0:
            cal[i] -= 1
            dfs(level+1, operator+ope[i])
            cal[i] += 1
 
for tc in range(1, t+1):
    N = int(input())
    cal = list(map(int, input().split()))
    num = list(map(int, input().split()))
    ope = ['+', '-', '*', '/']
    limit = sum(cal)
    Max = -1e8
    Min = 1e8
    dfs(0, '') # level, ์—ฐ์‚ฐ์ž
    print(f'#{tc} {Max-Min}')