#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1000010;
int h[N], e[N], ne[N], w[N], idx;
int dist[N];
bool state[N];
int n, m;
typedef pair<int, int> PII; // dist, index
void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int Dijkstra() {
memset(dist, 0x3f, sizeof(dist));
dist[1] = 0;
priority_queue<PII, vector<PII>, greater<PII>> q;
q.push({0, 1});
while (q.size()) {
auto t = q.top(); // 找出距离源点最近的节点
q.pop();
int ver = t.second, distance = t.first;
if (!state[ver]) state[ver] = true;
else continue;
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];
}
q.push({dist[j], j});
}
}
if (dist[n] == 0x3f3f3f3f) return -1;
else return dist[n];
}
int main(void)
{
memset(h, -1, sizeof(h));
cin >> n >> m;
while (m--) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
cout << Dijkstra() << endl;
return 0;
}