음..
DP로 풀었다. 계단문제랑 비슷하다.
처음에는 그냥 3나눠지면 3하고 2되면 2하고 했는데, 그게 아니라 경우의수가 최소일 때 를 구하는것 이였다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
/** | |
* BOJ 12852 1로 만들기 2 | |
* https://gist.github.com/KSH-code/97ac76b0518de5a02806170c11ab1a57 | |
*/ | |
public class Main{ | |
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); | |
private static int dp[][] = new int[(int)(1e+6)+1][2]; | |
public static void main(String[] args) throws IOException{ | |
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
int N = Integer.parseInt(br.readLine()); | |
for(int i = 0; i<dp.length; i++){ | |
dp[i][0] = Integer.MAX_VALUE; | |
} | |
dp[N][0] = 0; | |
calc(N); | |
bw.write(dp[1][0] + "\n"); | |
Stack<Integer> list = new Stack<>(); | |
int i = 1; | |
if(N == 2){ | |
bw.write("2 "); | |
}else{ | |
while(list.size() != dp[1][0]){ | |
list.push(i = dp[i][1]); | |
} | |
while(!list.isEmpty()){ | |
bw.write(list.pop() + " "); | |
} | |
} | |
bw.write("1"); | |
bw.flush(); | |
} | |
private static void calc(int N) throws IOException { | |
if(N == 1){ | |
return; | |
} | |
if(N % 3 == 0){ | |
if(dp[N / 3][0] >= dp[N][0] + 1){ | |
dp[N / 3][0] = dp[N][0] + 1; | |
dp[N / 3][1] = N; | |
calc(N / 3); | |
} | |
} | |
if(N % 2 == 0){ | |
if(dp[N / 2][0] >= dp[N][0] + 1){ | |
dp[N / 2][0] = dp[N][0] + 1; | |
dp[N / 2][1] = N; | |
calc(N / 2); | |
} | |
} | |
if(dp[N - 1][0] >= dp[N][0] + 1){ | |
dp[N - 1][0] = dp[N][0] + 1; | |
dp[N - 1][1] = N; | |
calc(N - 1); | |
} | |
} | |
} |
그래서 메모이제이션이랑 Stack을 이용해서 경로구하는거 까지 구현했다.
'IT > 알고리즘' 카테고리의 다른 글
BOJ 2042 구간 합 구하기 풀이 (0) | 2017.10.24 |
---|---|
BOJ 2589 풀이 (Olympiad > 한국정보올림피아드시․도지역본선 > 지역본선 2005 > 초등부 3번) (0) | 2017.10.23 |
2611 자동차경주 풀이 (Olympiad > 한국정보올림피아드시․도지역본선 > 지역본선 2004 > 중등부 5번) (0) | 2017.10.20 |
BOJ 2016 풀이 2004 (한국정보올림피아드시․도지역본선) (0) | 2017.10.19 |
BOJ 11657 타임머신 풀이 벨만 포드 (0) | 2017.10.19 |