Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
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
Tags
more
Archives
Today
Total
관리 메뉴

main

[백준-1463번/Java] 1로 만들기 본문

Algorithm

[백준-1463번/Java] 1로 만들기

1984 2022. 11. 15. 12:50

* 다이나믹 프로그래밍

* 1부터 N까지 3가지 연산의 최소 연산 횟수를 비교하면서 저장한다. (1의 경우는 연산횟수가 0이다.)

* 이전 연산이 없는 경우 예외 처리

import java.io.*;
import java.util.*;

public class Main {

	public static void main(String[] args) throws IOException {

		Scanner scan = new Scanner(System.in);

		int N = scan.nextInt();
		int count = 0;

		int[] dp = new int[N + 1];

		for (int i = 2; i < dp.length; i++) {

			int case1 = i % 2 == 0 ? (i / 2 > 1 ? dp[i / 2] : 0) : 1000001;
			int case2 = i % 3 == 0 ? (i / 3 > 1 ? dp[i / 3] : 0) : 1000001;
			int case3 = i - 1 > 0 ? dp[i - 1] : 0;

			dp[i] = Math.min(Math.min(case1, case2), case3) + 1;
		}

		System.out.println(dp[N]);
	}

}

 

728x90
Comments