728x90
1463번: 1로 만들기
첫째 줄에 1보다 크거나 같고, 106보다 작거나 같은 정수 N이 주어진다.
www.acmicpc.net
package 백준renew;
import java.io.*;
import java.util.*;
public class 실버3_1463_1로만들기 {
static int N;
static int arr[];
static boolean visited[];
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
N = Integer.parseInt(br.readLine());
arr = new int[1000001];
visited = new boolean[1000001];
Go(N);
System.out.println(arr[1]);
}
static void Go(int N) {
Queue<Integer> queue = new LinkedList<>();
queue.offer(N);
visited[N] = true;
while(!queue.isEmpty()) {
int now = queue.poll();
int tmp = 0;
for(int i=0; i<3; i++) {
if(i == 0) {
if(now%3 == 0) {
tmp = now / 3;
}else {
continue;
}
}else if(i == 1) {
if(now%2 == 0) {
tmp = now / 2;
}else {
continue;
}
}else {
tmp = now - 1;
}
if(tmp < 0 || visited[tmp]) {
continue;
}
arr[tmp] = arr[now] + 1;
queue.offer(tmp);
visited[tmp] = true;
}
}
}
}
728x90
'코테 > Algorithm' 카테고리의 다른 글
[BOJ] 17202: 핸드폰 번호 궁합 (JAVA) (0) | 2024.04.06 |
---|---|
[BOJ] 1463: 1로 만들기 - DP (JAVA) (0) | 2024.04.04 |
[BOJ] 1024: 수열의 합 - 최적화 (JAVA) (2) | 2024.04.03 |
[BOJ] 17413: 단어 뒤집기 2 (JAVA) (0) | 2024.04.02 |
[BOJ] 1024: 수열의 합 (JAVA) (0) | 2024.04.02 |