๋ค์ต์คํธ๋ผ๋ก ํ ์ ์๋ ๋ฌธ์ ์ํฉ
- ํ ์ง์ ์์ ๋ค๋ฅธ ํ ์ง์ ๊น์ง์ ์ต๋จ ๊ฒฝ๋ก
- ํ ์ง์ ์์ ๋ค๋ฅธ ๋ชจ๋ ์ง์ ๊น์ง์ ์ต๋จ ๊ฒฝ๋ก
- ๋ชจ๋ ์ง์ ์์ ๋ค๋ฅธ ๋ชจ๋ ์ง์ ๊น์ง์ ์ต๋จ ๊ฒฝ๋ก
ํด๋น ๋ฌธ์ ๋ ํ ์ง์ ์์ ๋ค๋ฅธ ํ ์ง์ ๊น์ง์ ์ต๋จ ๊ฒฝ๋ก๋ฅผ ๊ตฌํด์ผ ํ๋ ๋ฌธ์ ์ด๋ค.
๋ฌธ์ ๋ฅผ ๊ทธ๋ํ๋ก ๋ฐ๊พธ๋๊ฒ ์ค์ํ๋ค๊ณ ์๊ฐํ๋ค.
์๋น์ด๋ ์์น X์์ -1, +1, *2 ๋ก ์์ง์ผ ์ ์์ผ๋๊น
์์น X๋ฅผ ๋ ธ๋๋ผ๊ณ ์๊ฐํ์ ๋ X-1, X+1, X*2 ๋ฅผ ์ฐ๊ฒฐ๋ ๋ ธ๋, ๊ฐ์ค์น๋ ๋ฌธ์ ์์ ์ฃผ์ด์ง (1, 1, 0) ์ผ๋ก ์๊ฐํ๋ค.
๋ค์ต์คํธ๋ผ ์๊ณ ๋ฆฌ์ฆ (์ฐ์ ์์ํ ํ์ฉ) ์ฝ๋
package com.mincheolsong;
import java.io.*;
import java.util.*;
public class Main {
// boj 13549 ์จ๋ฐ๊ผญ์ง
static final int INF = (int)1e9;
static int N,K;
static int[] dist;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
if(N>=K){
System.out.println(N-K);
return;
}
dist = new int[100001];
Arrays.fill(dist,INF);
PriorityQueue<Point> pq = new PriorityQueue<>();
pq.offer(new Point(N,0));
dist[N]=0;
while(!pq.isEmpty()){
Point current = pq.poll();
if(current.x == K){
System.out.println(current.w); // ์ ๋ต ์ถ๋ ฅ
break;
}
if(dist[current.x] < current.w) continue; // ๋ฐฉ๋ฌธ์ฒดํฌ
// -1 ์์น๋ก ์ด๋ํ๋ ๊ฒฝ์ฐ (1์ด ๊ฑธ๋ฆผ)
if(current.x - 1 >= 0 && current.w + 1 < dist[current.x - 1]){
dist[current.x - 1] = current.w + 1;
pq.offer(new Point(current.x - 1,current.w + 1));
}
// +1 ์์น๋ก ์ด๋ํ๋ ๊ฒฝ์ฐ (1์ด ๊ฑธ๋ฆผ)
if(current.x + 1 <= 100000 && current.w + 1 < dist[current.x + 1]){
dist[current.x + 1] = current.w + 1;
pq.offer(new Point(current.x + 1,current.w + 1));
}
// *2 ์์น๋ก ์ด๋ํ๋ ๊ฒฝ์ฐ (0์ด ๊ฑธ๋ฆผ)
if(current.x * 2 <= 100000 && current.w + 0 < dist[current.x * 2]){
dist[current.x * 2] = current.w;
pq.offer(new Point(current.x * 2, current.w));
}
}
}
}
class Point implements Comparable<Point>{
int x,w;
public Point(int x,int w){
this.x = x;
this.w = w;
}
@Override
public int compareTo(Point o){
return this.w - o.w;
}
}
'๐์ฝ๋ฉํ ์คํธ:CodingTest' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋ค์ต์คํธ๋ผ (boj 12851 ์จ๋ฐ๊ผญ์ง2) (0) | 2024.01.02 |
---|---|
์ด์ง ๊ฒ์ ํธ๋ฆฌ (๋ฐฑ์ค 5639๋ฒ) (0) | 2023.12.28 |
ํธ๋ฆฌ์ ์ง๋ฆ (๋ฐฑ์ค 1167๋ฒ) (2) | 2023.12.26 |
ํ๋ก์ด๋ ์์ ์๊ณ ๋ฆฌ์ฆ (0) | 2023.12.14 |
๋ฐฑ์ค 9465 ์คํฐ์ปค (2) | 2023.11.29 |