파이썬 알고리즘 : 연산자 끼워넣기, 빙산, 구슬 찾기

2023년 8월 10일 알고리즘 문제풀이 문제 1 백준 14888 문제 링크 1차 시도 나의 생각 각 경우에 알맞은 연산을 처리한 후 재귀를 탔다. 정의한 dfs 재귀 함수는 몇번의 재귀를 탔는지, 각 연산이 몇번 남아있는지를 parameter로 받도록 정의하였다. 나눗셈은 음수일때는 양수로 변환한 후 결과에 음수를 다시 붙이도록 하였다. 결과 정답 코드 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 import sys n = int(sys.stdin.readline()) nums = list(map(int, sys.stdin.readline().split())) plus, minus, multiple, division = map(int, sys.stdin.readline().split()) arr = [] def dfs(tmp, cnt, a, b, c, d): if cnt == n: arr.append(tmp) return if a: tmp += nums[cnt] a -= 1 cnt += 1 dfs(tmp, cnt, a, b, c, d) cnt -= 1 a += 1 tmp -= nums[cnt] if b: tmp -= nums[cnt] b -= 1 cnt += 1 dfs(tmp, cnt, a, b, c, d) cnt -= 1 b += 1 tmp += nums[cnt] if c: tmp *= nums[cnt] c -= 1 cnt += 1 dfs(tmp, cnt, a, b, c, d) cnt -= 1 c += 1 tmp = tmp // nums[cnt] if d: if tmp >= 0: tmp = tmp//nums[cnt] else: r_tmp = abs(tmp)//nums[cnt] tmp = -1 * r_tmp d -= 1 cnt += 1 dfs(tmp, cnt, a, b, c, d) cnt -= 1 d += 1 if tmp >= 0: tmp = abs(tmp)*nums[cnt] else: r_tmp = abs(tmp)*nums[cnt] tmp = -1 * r_tmp dfs(nums[0], 1, plus, minus, multiple, division) print(max(arr)) print(min(arr)) 문제 2 백준 2573 문제 링크 ...

2023년 8월 10일 · 9 분 · 배준수