|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +public class Main { |
| 5 | + static List<Pair>[] adj; |
| 6 | + static int n; |
| 7 | + static int m; |
| 8 | + static int s; |
| 9 | + static int e; |
| 10 | + |
| 11 | + static class Pair implements Comparable<Pair>{ |
| 12 | + int cost,v; |
| 13 | + |
| 14 | + public Pair(int cost,int v){ |
| 15 | + this.cost = cost; |
| 16 | + this.v = v; |
| 17 | + } |
| 18 | + |
| 19 | + @Override |
| 20 | + public int compareTo(Pair o) { |
| 21 | + return this.cost - o.cost; |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + static void solutions(){ |
| 26 | + int[] prev = new int[n+2]; |
| 27 | + int[] d = new int[n+2]; |
| 28 | + Arrays.fill(d,0x3fffffff); |
| 29 | + PriorityQueue<Pair> pq = new PriorityQueue<>(); |
| 30 | + for(Pair p : adj[s]){ |
| 31 | + if(d[p.v] > p.cost){ |
| 32 | + pq.add(p); |
| 33 | + d[p.v] = p.cost; |
| 34 | + prev[p.v] = s; |
| 35 | + } |
| 36 | + } |
| 37 | + d[s] = 0; |
| 38 | + prev[s] = 0; |
| 39 | + while(!pq.isEmpty()){ |
| 40 | + var cur = pq.poll(); |
| 41 | + if(d[cur.v] != cur.cost) continue;; |
| 42 | + for(Pair nxt : adj[cur.v]){ |
| 43 | + if(d[nxt.v] > cur.cost + nxt.cost){ |
| 44 | + pq.add(new Pair(cur.cost + nxt.cost, nxt.v)); |
| 45 | + d[nxt.v] = cur.cost + nxt.cost; |
| 46 | + prev[nxt.v] = cur.v; |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + System.out.println(d[e]); |
| 51 | + List<Integer> path = new ArrayList<>(); |
| 52 | + int p = prev[e]; |
| 53 | + path.add(e); |
| 54 | + while(p != 0){ |
| 55 | + path.add(p); |
| 56 | + p = prev[p]; |
| 57 | + } |
| 58 | + System.out.println(path.size()); |
| 59 | + for(int i = path.size()-1 ;i>= 0 ;i--){ |
| 60 | + System.out.printf(path.get(i) + " "); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + static void input() throws IOException { |
| 65 | + try(var br = new BufferedReader(new InputStreamReader(System.in))){ |
| 66 | + var st = new StringTokenizer(br.readLine()); |
| 67 | + n = Integer.parseInt(st.nextToken()); |
| 68 | + st = new StringTokenizer(br.readLine()); |
| 69 | + m = Integer.parseInt(st.nextToken()); |
| 70 | + adj = new ArrayList[n+10]; |
| 71 | + for(int i=1;i<=n;i++) adj[i] = new ArrayList<>(); |
| 72 | + for(int i=0;i<m;i++) { |
| 73 | + st = new StringTokenizer(br.readLine()); |
| 74 | + int u = Integer.parseInt(st.nextToken()); |
| 75 | + int v = Integer.parseInt(st.nextToken()); |
| 76 | + int w = Integer.parseInt(st.nextToken()); |
| 77 | + adj[u].add(new Pair(w,v)); |
| 78 | + } |
| 79 | + st = new StringTokenizer(br.readLine()); |
| 80 | + s = Integer.parseInt(st.nextToken()); |
| 81 | + e = Integer.parseInt(st.nextToken()); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + public static void main(String[] args) throws IOException { |
| 86 | + input(); |
| 87 | + solutions(); |
| 88 | + } |
| 89 | +} |
0 commit comments