fork download
  1. import java.util.*;
  2. import java.io.*;
  3. public class Main
  4. {
  5. public static int Vertex=0,Edge=0;
  6. public static ArrayList<List>[] Map;
  7. public static int[] dist;
  8. public static void main(String[] args)throws IOException
  9. {
  10. StringTokenizer st = new StringTokenizer(br.readLine()," ");
  11. Vertex=Integer.parseInt(st.nextToken());Edge=Integer.parseInt(st.nextToken());
  12. int start = Integer.parseInt(br.readLine()),i=0,v1=0,v2=0,distance=0;
  13. Map = new ArrayList[Vertex+1];
  14. dist= new int[Vertex+1];
  15.  
  16. for(i=1;i<=Vertex;i++)
  17. {
  18. Map[i]=new ArrayList<>();
  19. dist[i] = Integer.MAX_VALUE-1;
  20. }
  21. for(i=0;i<Edge;i++)
  22. {
  23. st=new StringTokenizer(br.readLine()," ");
  24. v1=Integer.parseInt(st.nextToken());
  25. v2=Integer.parseInt(st.nextToken());
  26. distance=Integer.parseInt(st.nextToken());
  27. Map[v1].add(new List(v2,distance));
  28. }
  29. Djikstra(start);
  30. for(i=1;i<=Vertex;i++)
  31. {
  32. if(dist[i] != Integer.MAX_VALUE-1)
  33. System.out.println(dist[i]);
  34. else
  35. System.out.println("INF");
  36. }
  37. }
  38. public static void Djikstra(int start)
  39. {
  40. int i=0,now=0,now_dist=0,next=0,next_dist=0;
  41. PriorityQueue<List> pq = new PriorityQueue<>();
  42.  
  43. dist[start]=0;
  44. for(i=0;i<Map[start].size();i++)
  45. {
  46. now=Map[start].get(i).index;
  47. now_dist=Map[start].get(i).dist;
  48.  
  49. dist[now]=now_dist;
  50. pq.add(new List(now,dist[now]));
  51. }
  52. while(!pq.isEmpty())
  53. {
  54. List temp = pq.poll();
  55. now=temp.index;
  56. now_dist=dist[now];
  57.  
  58. for(i=0;i<Map[now].size();i++)
  59. {
  60. next=Map[now].get(i).index;
  61. next_dist=Map[now].get(i).dist+now_dist;
  62. if(dist[next]>next_dist)
  63. {
  64. dist[next]=next_dist;
  65. pq.add(new List(next,dist[next]));
  66. }
  67. }
  68. }
  69. }
  70. }
  71. class List implements Comparable<List>
  72. {
  73. int index=0;
  74. int dist=0;
  75. List(int index,int dist)
  76. {
  77. this.index=index;
  78. this.dist=dist;
  79. }
  80. public int compareTo(List o)
  81. {
  82. return this.dist<=o.dist?-1:1;
  83. }
  84. }
Success #stdin #stdout 0.06s 32888KB
stdin
2 2
1
1 2 1
1 2 2
stdout
0
2