#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N = 1e6 + 10;
typedef pair<int, int> PII;
int dist[N];
bool st[N];
int idx, w[N], h[N], e[N], ne[N];
int n, m;
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);
priority_queue<PII, vector<PII>, greater<PII> > q;
dist[1] = 0;
q.push({0, 1});
while(!q.empty()) {
auto t = q.top();
q.pop();
int distance = t.first, ver = t.second;
if(!st[ver]) {
st[ver] = 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];
q.push({dist[j], j});
}
}
}
}
if(dist[n] == 0x3f3f3f3f) return -1;
else return dist[n];
}
int main() {
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;
}