import java.util.Comparator; import java.util.PriorityQueue; import java.util.Scanner; /** * O(m * log(n)) */ public class Main { private static final int INF = Integer.MAX_VALUE; static class Item { int no; int dist; public Item(int no, int dist) { this.no = no; this.dist = dist; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); int m = in.nextInt(); int edgeIndex = 0; int[] lastEdge = new int[n + 1]; int[] weight = new int[m + 1]; int[] end = new int[m + 1]; int[] previousEdge = new int[m + 1]; while (m -- > 0) { int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); ++ edgeIndex; weight[edgeIndex] = c; end[edgeIndex] = b; previousEdge[edgeIndex] = lastEdge[a]; lastEdge[a] = edgeIndex; } int[] dist = new int[n + 1]; dist[1] = 0; for (int i = 2; i <= n; ++ i) { dist[i] = INF; } PriorityQueue<Item> queue = new PriorityQueue<>(new Comparator<Item>() { @Override public int compare(Item o1, Item o2) { return o1.dist - o2.dist; } }); queue.add(new Item(1, 0)); while (! queue.isEmpty()) { Item top = queue.poll(); for (int i = lastEdge[top.no]; i != 0; i = previousEdge[i]) { if (dist[end[i]] > dist[top.no] + weight[i]) { dist[end[i]] = dist[top.no] + weight[i]; queue.add(new Item(end[i], dist[end[i]])); } } } System.out.println(dist[n] == INF ? -1 : dist[n]); } } }