Notice
Recent Posts
Recent Comments
Today
Total
01-11 00:44
Link
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Partially Committed

[๋ฐฑ์ค€ 1463] 1๋กœ ๋งŒ๋“ค๊ธฐ (JAVA) ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm || ๋ฌธ์ œํ’€์ด/PS

[๋ฐฑ์ค€ 1463] 1๋กœ ๋งŒ๋“ค๊ธฐ (JAVA)

WonderJay 2023. 1. 27. 11:33
728x90
๋ฐ˜์‘ํ˜•
SMALL

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

 

1463๋ฒˆ: 1๋กœ ๋งŒ๋“ค๊ธฐ

์ฒซ์งธ ์ค„์— 1๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 106๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ •์ˆ˜ N์ด ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net

์ •์ˆ˜ n ์„ 1๋กœ ๋งŒ๋“ค๊ธฐ ์œ„ํ•œ ์—ฐ์‚ฐ ํšŸ์ˆ˜์˜ ์ตœ์†Ÿ๊ฐ’์„ dp[n] ์ด๋ผ๊ณ  ๊ฐ€์ •ํ•˜์ž. 

 

๊ทธ๋Ÿฌ๋ฉด dp[0] = dp[1] = 0, dp[2] = 1, dp[3] = 1

 

dp table ์„ ์•„๋ž˜์™€ ๊ฐ™์ด bottom-up ๋ฐฉ์‹์œผ๋กœ ์ฑ„์›Œ๋‚˜๊ฐˆ ์ˆ˜ ์žˆ๋‹ค.

 

1. N ์— ๋Œ€ํ•˜์—ฌ N-1 ์ด ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด dp[n] = dp[n-1]+1

2. N ์ด 2๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋ฉด dp[n] ์€ dp[n/2]+1 ์™€ dp[n-1]+1 ์ค‘ ๋” ์ž‘์€ ๊ฐ’์„ ์„ ํƒ

3. N ์ด 3์œผ๋กœ ๋‚˜๋ˆ„์–ด ๋–จ์–ด์ง€๋ฉด dp[n] ์€ dp[n/3]+1 ์™€ dp[n-1]+1 ์ค‘ ๋” ์ž‘์€ ๊ฐ’์„ ์„ ํƒ

 

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws IOException {
        System.setIn(new FileInputStream("src/input.txt"));
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] dp = new int[1000001];
        dp[0] = 0;
        dp[1] = 0;
        dp[2] = 1;
        dp[3] = 1;
        for(int i = 4 ; i<=n ; i++){
            dp[i] = dp[i-1]+1;
            if(i%3==0){
                dp[i] = Math.min(dp[i/3]+1, dp[i]);
            }
            if(i%2==0){
                dp[i] = Math.min(dp[i/2]+1, dp[i]);
            }
        }
        System.out.println(dp[n]);
    }
}
728x90
๋ฐ˜์‘ํ˜•
LIST
Comments