import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main {
static final int N = 150010;
static int n, m; //結點數,邊數
static int[] h, e, ne, w; //鄰接表適合表示稀疏圖,w用來存每個邊權重
static int idx;
static int[] dist;
static boolean[] status = new boolean[N]; //是否已確定最短路,最好直接賦值,這樣默認是false
static final int DIST = 0x3f3f3f3f; //>10^9,大于所有距離之和,可用來表示正無窮
//升序比較器
static Comparator> cmp = new Comparator>() {
public int compare(Pairss p1, Pairss p2) {
return (int)p1.getKey() - (int)p2.getKey();
}
};
//默認最小堆,由于內容是Pairss,因此需要比較器。
//用堆來存儲結點的距離和編號,被更新過距離的邊會被加入堆,表示可到達
static PriorityQueue> heap = new PriorityQueue<>(cmp);
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
String[] s = reader.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
h = new int[n+1];
e = new int[m];
ne = new int[m];
w = new int[m];
dist = new int[n+1];
Arrays.fill(h, -1);
Arrays.fill(dist, 1,n+1,DIST);
//不需要對重邊和自環做特殊處理,因為算法保證了最短路
while (m-- != 0) {
s = reader.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
int c = Integer.parseInt(s[2]);
add(a,b,c);
}
int t = dijkstra();
log.write(t + "");
log.flush();
log.close();
reader.close();
}
private static void add(int a, int b, int c) {
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx++;
}
private static int dijkstra() {
dist[1] = 0;
heap.add(new Pairss<>(0,1)); //1號點,距離為0
while(!heap.isEmpty()) {
Pairss t = heap.remove();
int ver = t.getValue(); int distance = t.getKey();
if(ver == n) break; //結點n已經確定最短路,結束程序
if(status[ver]) continue; //該值是個冗余備份,pop出的這個結點已經確定最短路徑,因此可以continue了
status[ver] = true; //將這個被選中的結點狀態設置為true,表示加入已確定最短路徑的點的集合
for (int i = h[ver]; i != -1; i = ne[i]) { //更新該結點的出邊指向的點的距離
int j = e[i];
if(dist[j] > distance + w[i]) {
dist[j] = distance + w[i];
heap.add(new Pairss<>(dist[j],j));
}
}
}
if(dist[n] == 0x3f3f3f3f) return -1;
return dist[n];
}
}
class Pairss {
private T1 key;
private T2 value;
public Pairss(T1 t1,T2 t2) {
key = t1;
value = t2;
}
public T1 getKey() {
return key;
}
public T2 getValue() {
return value;
}
}