Algorithm/📊 Problem Solving

[백준/BOJ] 9184 - 신나는 함수 실행

posted by sangmin

9184 - 신나는 함수 실행

문제

재귀 호출만 생각하면 신이 난다! 아닌가요?

다음과 같은 재귀함수 w(a, b, c)가 있다.

if a <= 0 or b <= 0 or c <= 0, then w(a, b, c) returns:
    1

if a > 20 or b > 20 or c > 20, then w(a, b, c) returns:
    w(20, 20, 20)

if a < b and b < c, then w(a, b, c) returns:
    w(a, b, c-1) + w(a, b-1, c-1) - w(a, b-1, c)

otherwise it returns:
    w(a-1, b, c) + w(a-1, b-1, c) + w(a-1, b, c-1) - w(a-1, b-1, c-1)

위의 함수를 구현하는 것은 매우 쉽다. 하지만, 그대로 구현하면 값을 구하는데 매우 오랜 시간이 걸린다. (예를 들면, a=15, b=15, c=15)

a, b, c가 주어졌을 때, w(a, b, c)를 출력하는 프로그램을 작성하시오.

코드

def w(a, b, c):
    if a <= 0 or b <= 0 or c <= 0:
        return 1

    if a > 20 or b > 20 or c > 20:
        if not dp[a][b][c]:
            dp[a][b][c] = w(20, 20, 20)
        return dp[a][b][c]

    if a < b < c:
        if not dp[a][b][c]:
            dp[a][b][c] = w(a, b, c-1) + w(a, b-1, c-1) - w(a, b-1, c)
        return dp[a][b][c]
    else:
        if not dp[a][b][c]:
            dp[a][b][c] = w(a-1, b, c) + w(a-1, b-1, c) + w(a-1, b, c-1) - w(a-1, b-1, c-1)
        return dp[a][b][c]


arr = []
while True:
    a, b, c = map(int, input().split())

    if a == -1 and b == -1 and c == -1:
        break

    arr.append([a, b, c])

maximum = 0
for i in range(len(arr)):
    maximum = max(maximum, max(arr[i]))

dp = [[[0 for _ in range(maximum+1)] for _ in range(maximum+1)] for _ in range(maximum+1)]

for a, b, c in arr:
    print('w({}, {}, {}) = {}'.format(a, b, c, w(a, b, c)))

한마디

memoization 기법을 이용하여 DP 테이블에 저장해뒀다.

 

9184번: 신나는 함수 실행

입력은 세 정수 a, b, c로 이루어져 있으며, 한 줄에 하나씩 주어진다. 입력의 마지막은 -1 -1 -1로 나타내며, 세 정수가 모두 -1인 경우는 입력의 마지막을 제외하면 없다.

www.acmicpc.net

 

'Algorithm > 📊 Problem Solving' 카테고리의 다른 글

[백준/BOJ] 17845 - 수강 과목  (0) 2021.02.13
[백준/BOJ] 4781 - 사탕 가게  (0) 2021.02.13
[백준/BOJ] 15990 - 1, 2, 3 더하기 5  (0) 2021.02.12
[백준/BOJ] 7579 - 앱  (0) 2021.02.09
[백준/BOJ] 14728 - 벼락치기  (0) 2021.02.09