|
| 1 | +package Graph.P1753; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + |
| 8 | + final static int INF = Integer.MAX_VALUE; |
| 9 | + static int V, E, K; |
| 10 | + static ArrayList<Node>[] graph; |
| 11 | + static int[] D; |
| 12 | + |
| 13 | + public static void main(String[] args) throws Exception { |
| 14 | + System.setIn(new FileInputStream("src/Graph/P1753/input.txt")); |
| 15 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 16 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 17 | + |
| 18 | + V = stoi(st.nextToken()); |
| 19 | + E = stoi(st.nextToken()); |
| 20 | + K = stoi(br.readLine()); |
| 21 | + |
| 22 | + graph = new ArrayList[V+1]; |
| 23 | + for (int i = 1; i <= V; i++) graph[i] = new ArrayList<>(); |
| 24 | + while (E-- > 0) { |
| 25 | + st = new StringTokenizer(br.readLine()); |
| 26 | + int u = stoi(st.nextToken()), v = stoi(st.nextToken()), w = stoi(st.nextToken()); |
| 27 | + graph[u].add(new Node(v, w)); |
| 28 | + } |
| 29 | + |
| 30 | + D = new int[V+1]; |
| 31 | + Arrays.fill(D, INF); |
| 32 | + PriorityQueue<Node> pq = new PriorityQueue<>(((o1, o2) -> o1.dist - o2.dist)); |
| 33 | + |
| 34 | + pq.offer(new Node(K, 0)); |
| 35 | + D[K] = 0; |
| 36 | + while (!pq.isEmpty()) { |
| 37 | + Node current = pq.poll(); |
| 38 | + if (D[current.idx] < current.dist) continue; |
| 39 | + for (int i = 0; i < graph[current.idx].size(); i++) { |
| 40 | + Node next = graph[current.idx].get(i); |
| 41 | + if (D[next.idx] > D[current.idx] + next.dist) { |
| 42 | + D[next.idx] = D[current.idx] + next.dist; |
| 43 | + pq.offer(new Node(next.idx, D[next.idx])); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + for (int i = 1; i <= V; i++) { |
| 49 | + if (D[i] == INF) System.out.println("INF"); |
| 50 | + else System.out.println(D[i]); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + private static int stoi(String s) { return Integer.parseInt(s); } |
| 55 | + |
| 56 | + static class Node { |
| 57 | + int idx; |
| 58 | + int dist; |
| 59 | + |
| 60 | + public Node(int idx, int dist) { |
| 61 | + this.idx = idx; |
| 62 | + this.dist = dist; |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments