#include <cstring>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 160010;
typedef pair<int, int> PII;
int n, m;
int e[N], w[N], h[N], ne[N], idx;
int dist[N];
bool st[N];
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 distance = t.first, ver = t.second;
if (st[ver]) continue;
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});
}
// 如果dist[j] <= distance + w[i]说明存在一个 dist[j] 比当前的,利用最优点更新dist[j]的结果还要小;
// 因此该点j存在两个情况
// 1、已经放入st中,那么q.push在不在if语句中结果都一样,会在下次选择到的时候continue掉,push在if语句中会少执行一次;
// 2、还未放入st中,那么这个点之前被更新过一次,只要之前更新了就一定会放入q中,那么再讲j放入q中则多做了一次;
// 简而言之,每次只找到最优的点并只push能够利用最优点进行更新的点即可,若不能更新则不用管;
}
}
if (dist[n] == 0x3f3f3f3f) return -1;
return dist[n];
}
int main()
{
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while (m -- )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
cout << dijkstra() << endl;
return 0;
}