백준 - 9184번(신나는 함수 실행)

최지홍·2022년 3월 11일
0

백준

목록 보기
96/145

문제 출처: https://www.acmicpc.net/problem/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)를 출력하는 프로그램을 작성하시오.


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

public class Main {

    private static Map<String, Integer> map = new HashMap<>();

    public static void main(String[] args) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
            int a = Integer.parseInt(tokenizer.nextToken());
            int b = Integer.parseInt(tokenizer.nextToken());
            int c = Integer.parseInt(tokenizer.nextToken());

            if (a == -1 && a == b && b == c) break;

            sb.append("w(").append(a).append(", ").append(b).append(", ").append(c).append(") = ");
            sb.append(w(a, b, c)).append("\n");
        }

        System.out.println(sb);
    }

    private static int w(int a, int b, int c) {
        if (a <= 0 || b <= 0 || c <= 0) {
            return 1;
        }

        String temp = "" + a + "/" + b + "/" + c;

        if (map.containsKey(temp)) return map.get(temp); // 이미 알고 있는 값인 경우

        if (a > 20 || b > 20 || c > 20) {
            map.put(temp, w(20, 20, 20));
            return map.get(temp);
        }

        if (a < b && b < c) {
            map.put(temp, w(a, b, c - 1) + w(a, b - 1, c - 1) - w(a, b - 1, c));
            return map.get(temp);
        }

        map.put(temp, 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 map.get(temp);
    }

}

  • 메모이제이션을 통해 풀이하려 하였으나 처음에 시간 초과가 나왔다.
  • 처음에는 3개의 int 변수를 저장하는 객체를 만든 후, Comparable를 implement 하여 compare()를 오버라이딩 하여 이를 HashMap에 이용했는데 이렇게 진행하니 시간이 꽤 걸렸다. 사실 이 부분이 시간이 많이 걸린다는걸 상당히 늦게 알게 되었다.
  • 이 숫자들을 문자열로 하나로 묶어 HashMap에 저장하니 해결할 수 있었다.
  • 여기서 중요한 점은, 숫자를 문자열로 묶을 때 자릿수의 구분이 되지 않는다. 이를 신경써야 한다.
profile
백엔드 개발자가 되자!

0개의 댓글