Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import static java.lang.Integer.parseInt;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Comparator;
- import java.util.PriorityQueue;
- import java.util.Stack;
- import java.util.StringTokenizer;
- public class Main{
- static BufferedReader reader;
- static StringTokenizer tok;
- static int n, m, parents[];
- static boolean vistid[];
- static long cost[];
- static ArrayList<pair> graph[];
- static PriorityQueue<pair2> q;
- static Stack<Integer> s;
- static BufferedWriter writer;
- public static void main(String[] args) throws IOException {
- Input();
- sol();
- }
- public static void sol() throws IOException {
- writer = new BufferedWriter(new OutputStreamWriter(System.out));
- vistid = new boolean[n + 1];
- cost = new long[n + 1];
- parents = new int[n + 1];
- q = new PriorityQueue<pair2>(Comparator.comparing((pair2 obj)-> obj.wieght));
- q.add(new pair2(1, 0));
- vistid[1] = true;
- Arrays.fill(cost, Integer.MAX_VALUE);
- cost[1] = 0;
- while (!q.isEmpty()) {
- pair2 obj = q.poll();
- for (pair x : graph[obj.node]) {
- if (!vistid[x.node] || cost[x.node] > obj.wieght + x.wieght) {
- vistid[x.node] = true;
- parents[x.node] = obj.node;
- cost[x.node] = obj.wieght + x.wieght;
- q.add(new pair2(x.node, cost[x.node]));
- }
- }
- }
- s = new Stack<Integer>();
- int x = parents[n];
- if (x != 0) {
- while (x != 0) {
- s.push(x);
- x = parents[x];
- }
- while (!s.isEmpty()) {
- writer.write(s.pop() + " ");
- }
- writer.write(n + "");
- writer.flush();
- } else {
- System.out.println(-1);
- }
- }
- public static void Input() throws IOException {
- reader = new BufferedReader(new InputStreamReader(System.in));
- tok = new StringTokenizer(reader.readLine());
- n = parseInt(tok.nextToken());
- m = parseInt(tok.nextToken());
- graph = new ArrayList[n + 1];
- for (int i = 0; i <= n; i++) {
- graph[i] = new ArrayList<pair>();
- }
- for (int i = 0; i < m; i++) {
- tok = new StringTokenizer(reader.readLine());
- int a = parseInt(tok.nextToken()), b = parseInt(tok.nextToken()), wieght = parseInt(tok.nextToken());
- graph[a].add(new pair(b, wieght));
- graph[b].add(new pair(a, wieght));
- }
- }
- public static class pair {
- int node, wieght;
- public pair(int node, int wieght) {
- this.node = node;
- this.wieght = wieght;
- }
- }
- public static class pair2 {
- long wieght;
- int node;
- public pair2(int node, long wieght) {
- this.node = node;
- this.wieght = wieght;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement