๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][๋ฐฑ์ค€] 12852๋ฒˆ 1๋กœ ๋งŒ๋“ค๊ธฐ 2

๋ฐ˜์‘ํ˜•

[BOJ] 12852๋ฒˆ 1๋กœ ๋งŒ๋“ค๊ธฐ 2

https://www.acmicpc.net/problem/12852

์ ‘๊ทผ ๋ฐฉ๋ฒ•

์ฒ˜์Œ์—๋Š” dfs ๋ฐฉ๋ฒ•์œผ๋กœ ์žฌ๊ท€ ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด์„œ ์ ‘๊ทผ์„ ํ–ˆ๋Š”๋ฐ ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋‚˜์„œ
dp ๋ฐฉ์‹์œผ๋กœ ์ ‘๊ทผ ๋ฐฉ๋ฒ•์„ ๋ฐ”๊พธ์—ˆ๋‹ค.
dp[i]๋ฅผ ์šฐ์„  dp[i-1] +1๋กœ ํ•˜๊ณ , 2๋กœ ๋‚˜๋ˆ„์–ด์งˆ ๋•Œ์™€, 3์œผ๋กœ ๋‚˜๋ˆ„์–ด์งˆ ๋•Œ dp[i/2] + 1๊ณผ dp[i/3] + 1์„ ๋น„๊ตํ•ด์„œ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ dp[i]๋กœ ๊ฒฐ์ •ํ•˜์˜€๋‹ค.
i๋Š” 2๋ถ€ํ„ฐ n๊นŒ์ง€ ๋ฐ˜๋ณตํ•ด์„œ dp[n]์ผ ๋•Œ ์ตœ์†Ÿ๊ฐ’์„ ๊ตฌํ•˜์˜€๊ณ 
๋งŒ๋“œ๋Š” ์ ˆ์ฐจ๋ฅผ ์ถœ๋ ฅํ•˜๊ธฐ ์œ„ํ•ด์„œ ์œ„์— ํ–ˆ๋˜ ๋ฐฉ์‹์„ ๊ฑฐ๊พธ๋กœ ํ•ด์„œ ์ถœ๋ ฅํ•ด์ฃผ์—ˆ๋‹ค.

Code

import java.util.Scanner;

public class BOJ12852 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] dp = new int[n + 1];
        dp[0] = dp[1] = 0;
        for(int i = 2; i<=n; i++){
            dp[i] = dp[i-1] + 1;
            if(i%2 == 0){
                dp[i] = Math.min(dp[i], dp[i/2]+1);
            }
            if(i%3 == 0){
                dp[i] = Math.min(dp[i], dp[i/3]+1);
            }
        }
        System.out.println(dp[n]);
        StringBuilder sb = new StringBuilder();
        sb.append(n).append(" ");
        while(n>1){
            int min = dp[n-1];
            int temp = n-1;
            if(n%3 == 0 && dp[n/3] < min){
                min = dp[n/3];
                temp = n/3;
            }
            if(n%2 == 0 && dp[n/2] < min){
                min = dp[n/2];
                temp = n/2;
            }
            n = temp;
            sb.append(n).append(" ");

        }
        System.out.print(sb.toString().trim());
    }
}
๋ฐ˜์‘ํ˜•