fork download
  1. import java.util.*;
  2. import java.io.*;
  3.  
  4.  
  5. public class Main
  6. {
  7. static class node implements Comparable<node>
  8. {
  9. int goal;
  10. int cost;
  11.  
  12. public node(int goal , int cost)
  13. {
  14. this.goal = goal;
  15. this.cost = cost;
  16. }
  17.  
  18. public int compareTo(node n)
  19. {
  20. return cost - n.cost;
  21. }
  22. }
  23. static int n , m , x;
  24. static ArrayList<node>[] list;
  25. static PriorityQueue<node> pq; //매번하게 될 듯?
  26. static boolean[] visit; //매번하게 될 듯?
  27. static int[] value;
  28. static boolean arrive; //목적지 도착 후 돌아갈 타이밍을 알기 위한 장치
  29.  
  30. public static void main (String[] args) throws IOException
  31. {
  32. StringTokenizer st = new StringTokenizer(br.readLine());
  33.  
  34. n = Integer.parseInt(st.nextToken());
  35. m = Integer.parseInt(st.nextToken());
  36. x = Integer.parseInt(st.nextToken());
  37.  
  38. list = new ArrayList[n+1];
  39. value = new int[n+1];
  40.  
  41. for(int i = 1 ; i <= n ; i++)
  42. {
  43. list[i] = new ArrayList<>();
  44. if(i != x) value[i] = Integer.MAX_VALUE;
  45. }
  46.  
  47. for(int i = 0 ; i < m ; i++)
  48. {
  49. st = new StringTokenizer(br.readLine());
  50. int a = Integer.parseInt(st.nextToken());
  51. int b = Integer.parseInt(st.nextToken());
  52. int c = Integer.parseInt(st.nextToken());
  53.  
  54. list[b].add(new node(a,c));
  55. }
  56.  
  57. for(int i = 1 ; i <= n ; i++)
  58. {
  59. Collections.sort(list[i]);
  60. }
  61.  
  62. bfs(x);
  63.  
  64. int max = 0;
  65. for(int i = 1 ; i <= n ; i++)
  66. {
  67. //System.out.println(value[i]);
  68. max = Math.max(value[i],max);
  69. }
  70. System.out.println(max);
  71. }
  72. public static void bfs(int start)
  73. {
  74. visit = new boolean[n+1];
  75. arrive = false;
  76. pq = new PriorityQueue<>();
  77. pq.add(new node(start,0));
  78.  
  79. while(!pq.isEmpty())
  80. {
  81. node nod = pq.poll();
  82.  
  83. if(visit[nod.goal]) continue;
  84. visit[nod.goal] = true;
  85.  
  86. for(int i = 0 ; i < list[nod.goal].size() ; i++)
  87. {
  88. node next = list[nod.goal].get(i);
  89.  
  90. if(!visit[next.goal] && value[next.goal] > value[nod.goal] + next.cost)
  91. {
  92. value[next.goal] = value[nod.goal] + next.cost;
  93. pq.add(new node(next.goal , value[next.goal]));
  94. }
  95. }
  96. }
  97. }
  98. }
Success #stdin #stdout 0.09s 51404KB
stdin
4 8 2
1 2 4
1 3 2
1 4 7
2 1 1
2 3 5
3 1 2
3 4 4
4 2 3
stdout
6