๋ฐ์ํ
[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());
}
}
๋ฐ์ํ
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Algorithm/Java][๋ฐฑ์ค] 1987๋ฒ ์ํ๋ฒณ (0) | 2022.05.08 |
---|---|
[Algorithm/Java][๋ฐฑ์ค] 2467๋ฒ ์ฉ์ก (0) | 2022.05.03 |
[Algorithm/Java][ํ๋ก๊ทธ๋๋จธ์ค] ๋จ์ฒด์ฌ์ง ์ฐ๊ธฐ (0) | 2022.05.01 |
[Algortihm/Java][ํ๋ก๊ทธ๋๋จธ์ค] ์คํ์ฑํ ๋ฐฉ (0) | 2022.04.12 |
[Algorithm/Java][๋ฐฑ์ค] 2263 ํธ๋ฆฌ์ ์ํ (0) | 2022.04.11 |