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;
}
}