#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 1000010;
int n, m;
int h[N], e[N], ne[N], w[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>> heap;
heap.push({0, 1});
while (heap.size())
{
auto t = heap.top();
heap.pop();
int distance = t.first, ver = t.second; // 读出第一个点,就是最短的dist值的那个点
if (!st[ver]) // 实际上找的就是那个dist最小且st状态仍未被确定的点
{
st[ver] = true;
for (int i = h[ver]; i != -1; i = ne[i])
{
int nd = e[i];
if (dist[nd] > distance + w[i])
{
dist[nd] = distance + w[i];
heap.push({dist[nd], nd}); //只有被更新了点,才添加到里面//当然直接添加所有的点也可以,冗余情况更多。
}
}
}
}
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);
}
int t = dijkstra();
if (t == 0x3f3f3f3f) cout << -1;
else cout << t;
return 0;
}