Notice
Recent Posts
Recent Comments
05-21 07:17
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

Byeol Lo

N13549 - 숨바꼭질 3 본문

Algorithm/Dijkstra

N13549 - 숨바꼭질 3

알 수 없는 사용자 2024. 1. 14. 13:18
import java.util.Scanner;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.Arrays;


public class Main {
    final static Scanner SC = new Scanner(System.in);
    final static int upperBound = 200001;
    static HashMap<Integer, HashMap<Integer, int[]>> graph;
    static int dist[];
    static int v1, v2;

    public static void main(String[] args) {
        input();
    }

    static void input() {
        v1 = SC.nextInt();
        v2 = SC.nextInt();
        graph = new HashMap<>(upperBound);
        dist = new int[upperBound];
        if(v1>v2) {
            System.out.println(v1-v2);
            return;
        }
        Arrays.fill(dist, Integer.MAX_VALUE);
        for(int i=0; i<=upperBound; i++)
            graph.put(i, new HashMap<>());
        graph.get(0).put(1, new int[]{1, 1});
        graph.get(1).put(2, new int[]{2, 0});
        for(int i=2; i < upperBound; i++) {
            graph.get(i).put(i+1, new int[]{i+1, 1});
            graph.get(i).put(i-1, new int[]{i-1, 1});
            if(i*2 <= upperBound) graph.get(i).put(i*2, new int[]{i*2, 0});
        }
        solution(v1);
    }

    static void solution(int start) {
        int[] curVer, nextVer;
        PriorityQueue<int[]> path = new PriorityQueue<>(
                (v1, v2) -> v1[1] - v2[1]
        );
        dist[start] = 0;
        path.add(new int[]{start, dist[start]});

        while(!path.isEmpty()) {
            curVer = path.poll();
            if(dist[curVer[0]] < curVer[1]) continue;
            for(int key : graph.get(curVer[0]).keySet()) {
                nextVer = graph.get(curVer[0]).get(key);
                if(dist[nextVer[0]] > nextVer[1]+dist[curVer[0]]) {
                    dist[nextVer[0]] = nextVer[1]+dist[curVer[0]];
                    path.add(new int[]{nextVer[0], dist[nextVer[0]]});
                }
            }
        }

        System.out.println(dist[v2]);
    }
}

'Algorithm > Dijkstra' 카테고리의 다른 글

N1504 - 특정한 최단 경로  (0) 2024.01.14
N1753 - 최단경로  (0) 2023.12.27
N17396 - 백도어  (0) 2023.12.24
Comments