백준/JAVA

[백준/JAVA] 9184번 신나는 함수 실행

누룽지맛치킨 2023. 2. 10. 14:34

1. 문제

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

다음과 같은 재귀함수 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)를 출력하는 프로그램을 작성하시오.

2. 문제 접근

1) -1 -1 -1 가 입력되기 전까지 정수 a, b, c를 입력받는다.
2) 문제에서 주어진대로 입력을 a, b, c로 하는 함수 w를 실행한다.
3) 함수 w에서 위의 문제와 같이 작동하되 w(a,b,c)의 값을 w_data라는 3차원 int형 배열에 저장하여 다음에 불릴 때는 w_data의 값을 바로 적용되도록 한다.

3. 코드

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.StringTokenizer;

public class Main {

    static int w_data[][][] = new int[21][21][21];

    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;
        StringBuilder sb = new StringBuilder();
        while(true){
            st = new StringTokenizer(br.readLine());
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());
            int c = Integer.parseInt(st.nextToken());
            if(a == -1 && b == -1 && c==-1){
                break;
            }
            int result = w(a,b,c);
            sb.append("w("+a+", "+b+", "+c+") = " + result +"\n");
        }
        System.out.print(sb);
    }

    static int w(int a, int b, int c){
        if(a<=0 || b<=0 || c<=0){
            return 1;
        }
        else if(a>20 || b>20 || c>20){
            return w_data[20][20][20] = w(20,20,20);
        }
        else if(w_data[a][b][c] !=0){
            return w_data[a][b][c];
        }
        else if(a<b && b<c){
            return w_data[a][b][c] = w(a,b,c-1) + w(a,b-1,c-1) - w(a, b-1,c);
        }
        else{
            return  w_data[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);
        }
    }
}