sm 기술 블로그

126. 9184 (신나는 함수 실행) 본문

문제/백준_자바

126. 9184 (신나는 함수 실행)

sm_hope 2022. 7. 2. 12:03
import java.util.*;
import java.io.*;

class Main {
	static int[][][] memo;

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

		while (true) {
			String[] inputs = br.readLine().split(" ");
			int a = Integer.parseInt(inputs[0]);
			int b = Integer.parseInt(inputs[1]);
			int c = Integer.parseInt(inputs[2]);

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

			int tmp = w(a, b, c);

			sb.append("w(" + a + ", " + b + ", " + c + ") = " + tmp).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;
		}
		if (a > 20 || b > 20 || c > 20) {
			return w(20, 20, 20);
		}

		if (memo[a][b][c] > 0) {
			return memo[a][b][c];
		}

		if (a < b && b < c) {
			memo[a][b][c] = w(a, b, c - 1) + w(a, b - 1, c - 1) - w(a, b - 1, c);
			return memo[a][b][c];
		}

		memo[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 memo[a][b][c];
	}

}

문제요약

재귀함수를 동적프로그래밍으로 바꾸는 문제

설명

동적프로그래밍을 알면 크게 어렵지 않다.

동적프로그래밍의 개념은 아래를 참고하자.

https://smhope.tistory.com/328?category=1056187 

 

동적프로그래밍(Dynamic Programming)

동적프로그래밍(Dynamic Programming) 하나의 큰 문제를 여러 개의 작은 문제로 나누어서 그 결과를 저장하여 다시 큰 문제를 해결할 때 사용하는 것 다음과 같이 중복으로 계산하는 것을 줄여줌으로

smhope.tistory.com

if (memo[a][b][c] > 0) {
			return memo[a][b][c];
		}

메모에 기입되있다면 넘어간다.

 

'문제 > 백준_자바' 카테고리의 다른 글

128. 9461 (파도반 수열)  (0) 2022.07.03
127. 1904 (01타일)  (0) 2022.07.03
125. 24416(알고리즘 수업 - 피보나치 수 1)  (0) 2022.07.02
124. 14889(스타트와 링크)  (0) 2022.07.01
123. 14888(연산자 끼워놓기)  (0) 2022.07.01
Comments