#include <cstdio>
#include <cstring>
#include <queue>
#define max(a, b) (a > b ? a : b)
using namespace std;
const int N = 1e5 + 5, M = 1e5 + 5, INF = 0x3f3f3f3f;
struct E {
int v, w, next;
}e[M];
struct Node {
int v, d;
Node(int v, int d):v(v), d(d){}
bool operator < (const Node &w)const {
return d > w.d;
}
};
int n, m, len = 1, head[N], d[N];
bool vis[N];
void add(int u, int v, int w) {
e[len].v = v;
e[len].next = head[u];
e[len].w = w;
head[u] = len++;
}
void dijkstra(int u) {
memset(d, 0x3f, sizeof(d));
d[u] = 0;
priority_queue<Node> q;
q.push(Node(u, 0));
while (!q.empty()) {
u = q.top().v;
q.pop();
if (vis[u]) continue;
vis[u] = true;
for (int j = head[u]; j; j = e[j].next) {
int v = e[j].v;
int w = e[j].w;
if (!vis[v] && d[v] > d[u] + w) {
d[v] = d[u] +w;
q.push(Node(v, d[v]));
}
}
}
}
int main() {
scanf("%d%d", &n, &m);
int u, v, w;
for (int i = 1; i <= m; i++) {
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
}
dijkstra(1);
printf("%d\n", d[n] == INF ? -1 : d[n]);
return 0;
}