Advertisement
anasretdinov

Dijkstra

Mar 19th, 2020
311
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.98 KB | None | 0 0
  1. // Working program with FastReader
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.PrintWriter;
  6. import java.util.Scanner;
  7. import java.util.StringTokenizer;
  8. import java.util.Scanner;
  9. import java.util.*;
  10. public class Main {
  11.     static Scanner s = new Scanner(System.in);
  12.     static PriorityQueue<Pair> heap = new PriorityQueue<>();
  13.     static int n = s.nextInt();
  14.     static int m = s.nextInt();
  15.     static int [] dist = new int [n];
  16.     static int start = s.nextInt();
  17.     static ArrayList<Pair> [] a = new ArrayList[n];
  18.     static int [] used = new int [n];
  19.     public static void main(String[] args) {
  20.         start--;
  21.         for (int i = 0; i < n; i++) {
  22.             a[i] = new ArrayList<>();
  23.             if (i == start) heap.add(new Pair(0, i));
  24.             else{
  25.                 dist[i] = Integer.MAX_VALUE;
  26.             }
  27.         }
  28.         for (int i = 0; i < m; i++) {
  29.             int k1 = s.nextInt();
  30.             int k2 = s.nextInt();
  31.             int w = s.nextInt();
  32.             k1--;
  33.             k2--;
  34.             a[k1].add(new Pair(k2, w));
  35.             a[k2].add(new Pair(k1, w));
  36.         }
  37.         while (heap.size() != 0){
  38.             int p = heap.remove().y;
  39.             if (used[p] == 1) continue;;
  40.             used[p] = 1;
  41.             for (Pair iter:a[p]) {
  42.                 if (dist[p] + iter.y < dist[iter.x]){
  43.                     dist[iter.x] = dist[p] + iter.y;
  44.                     heap.add(new Pair(dist[iter.x], iter.x));
  45.                 }
  46.             }
  47.         }
  48.         for (int i = 0; i < n; i++) {
  49.             System.out.print(dist[i] + " ");
  50.         }
  51.         System.out.println();
  52.     }
  53. }
  54. class Pair implements Comparable<Pair>{
  55.     int x;
  56.     int y;
  57.     Pair(int x, int y){
  58.         this.x = x;
  59.         this.y = y;
  60.     }
  61.     public int compareTo(Pair p2) {
  62.         if (this.x == p2.x){
  63.             return this.y - p2.y;
  64.         }
  65.         else return this.x - p2.x;
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement