
π»Q
μ΄λ€ λλΌμλ 1λ²λΆν° Nλ²κΉμ§μ λμμ Mκ°μ λ¨λ°©ν₯ λλ‘κ° μ‘΄μ¬νλ€.
λͺ¨λ λλ‘μ 거리λ 1μ΄λ€.
μ΄ λ νΉμ ν λμ Xλ‘λΆν° μΆλ°νμ¬ λλ¬ν μ μλ λͺ¨λ λμ μ€μμ, μ΅λ¨ κ±°λ¦¬κ° μ νν KμΈ λͺ¨λ λμλ€μ λ²νΈλ₯Ό μΆλ ₯νλ νλ‘κ·Έλ¨μ μμ±νμμ€.
λν μΆλ° λμ Xμμ μΆλ° λμ Xλ‘ κ°λ μ΅λ¨ 거리λ νμ 0μ΄λΌκ³ κ°μ νλ€.
μλ₯Ό λ€μ΄ N=4, K=2, X=1μΌ λ λ€μκ³Ό κ°μ΄ κ·Έλνκ° κ΅¬μ±λμ΄ μλ€κ³ κ°μ νμ.

μ΄ λ 1λ² λμμμ μΆλ°νμ¬ λλ¬ν μ μλ λμ μ€μμ, μ΅λ¨ κ±°λ¦¬κ° 2μΈ λμλ 4λ² λμ λΏμ΄λ€.
2λ²κ³Ό 3λ² λμμ κ²½μ°, μ΅λ¨ κ±°λ¦¬κ° 1μ΄κΈ° λλ¬Έμ μΆλ ₯νμ§ μλλ€.
μ λ ₯
첫째 μ€μ λμμ κ°μ N, λλ‘μ κ°μ M, 거리 μ 보 K, μΆλ° λμμ λ²νΈ Xκ° μ£Όμ΄μ§λ€.
(2 ≤ N ≤ 300,000, 1 ≤ M ≤ 1,000,000, 1 ≤ K ≤ 300,000, 1 ≤ X ≤ N) λμ§Έ μ€λΆν° Mκ°μ μ€μ κ±Έμ³μ λ κ°μ μμ°μ A, Bκ° κ³΅λ°±μ κΈ°μ€μΌλ‘ ꡬλΆλμ΄ μ£Όμ΄μ§λ€.
μ΄λ Aλ² λμμμ Bλ² λμλ‘ μ΄λνλ λ¨λ°©ν₯ λλ‘κ° μ‘΄μ¬νλ€λ μλ―Έλ€.
(1 ≤ A, B ≤ N) λ¨, Aμ Bλ μλ‘ λ€λ₯Έ μμ°μμ΄λ€.
μΆλ ₯
Xλ‘λΆν° μΆλ°νμ¬ λλ¬ν μ μλ λμ μ€μμ, μ΅λ¨ κ±°λ¦¬κ° KμΈ λͺ¨λ λμμ λ²νΈλ₯Ό ν μ€μ νλμ© μ€λ¦μ°¨μμΌλ‘ μΆλ ₯νλ€.
μ΄ λ λλ¬ν μ μλ λμ μ€μμ, μ΅λ¨ κ±°λ¦¬κ° KμΈ λμκ° νλλ μ‘΄μ¬νμ§ μμΌλ©΄ -1μ μΆλ ₯νλ€.






π‘A
λ€μ΅μ€νΈλΌ νμ΄
import java.util.*; class Main { private static int N, M, K, X; private static int[] distance; //μΆλ°λμμΈ Xμμ μ΅λ¨κ²½λ‘ private static ArrayList<Edge>[] edgeList; //λμ μΈμ 리μ€νΈ public static void main(String[] args) { Scanner sc = new Scanner(System.in); N = sc.nextInt(); M = sc.nextInt(); K = sc.nextInt(); X = sc.nextInt(); //μμ± μ΄κΈ°ν distance = new int[N + 1]; edgeList = new ArrayList[N + 1]; Arrays.fill(distance, Integer.MAX_VALUE); for(int i=1; i<=N; i++) { edgeList[i] = new ArrayList<>(); } //κ²½λ‘ μ΄κΈ°ν for(int i=0; i<M; i++) { int start = sc.nextInt(); int end = sc.nextInt(); //Aλ² λμμμ Bλ² λμλ‘ μ΄λνλ λ¨λ°©ν₯ λλ‘κ° μ‘΄μ¬ edgeList[start].add(new Edge(end, 1)); } //μΆλ° λμ distance[X] = 0; dijkstra(); int answer = 0; for(int i=1; i<distance.length; i++){ int d = distance[i]; if(d==K) { System.out.println(i); answer++; } } if (answer==0) System.out.println(-1); } private static void dijkstra() { PriorityQueue<Edge> queue = new PriorityQueue<>(); queue.add(new Edge(X, 0)); while(!queue.isEmpty()) { Edge edge = queue.poll(); int vertex = edge.vertex; int cost = edge.cost; if(distance[vertex]<cost) { continue; } //ν΄λΉ λμμ μ°κ²° λμ΄ μλ λμλ€ νμ for(int i=0; i<edgeList[vertex].size(); i++) { int v = edgeList[vertex].get(i).vertex; int c = edgeList[vertex].get(i).cost + cost; //μ΅λ¨ κ²½λ‘ μ μ₯ if(distance[v]>c) { distance[v] = c; queue.add(new Edge(v, c)); } } } } private static class Edge implements Comparable<Edge> { int vertex; int cost; public Edge(int vertex, int cost) { this.vertex = vertex; this.cost = cost; } @Override public int compareTo(Edge o) { return cost - o.cost; } } }
'Algorithm > Baekjoon' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
| λ°±μ€ 15650 Nκ³Ό M(2) (0) | 2021.10.30 |
|---|---|
| [9μ£Όμ°¨] λ°±μ€ 10162 μ μλ μΈμ§ (0) | 2021.09.28 |
| [7μ£Όμ°¨] λ°±μ€ 2579 κ³λ¨ μ€λ₯΄κΈ° (0) | 2021.09.15 |
| [6μ£Όμ°¨] λ°±μ€ 10872 ν©ν λ¦¬μΌ (0) | 2021.09.02 |
| [6μ£Όμ°¨] λ°±μ€ 10829 μ΄μ§μ λ³ν (0) | 2021.09.01 |