#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
typedef pair<int, int>PII;
const int N = 250010;
int n, m;
int h[N], w[N], e[N], ne[N], idx;
int dis[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 dijkstrea()
{
memset(dis, 0x3f, sizeof (dis));
dis[1] = 0;
priority_queue<PII,vector<PII>,greater<PII>>heap;
//定义:priority_queue<Type, Container, Functional>
//升序队列
//priority_queue <int,vector<int>,greater<int> > q
//降序队列
//priority_queue <int,vector<int>,less<int> >q;
heap.push({0, 1});
//优先队列在pair按照第一个排序,所以第一个为距离,第二个是点数
while(heap.size())
{
auto t = heap.top();
heap.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(dis[j] > distance + w[i])
{
dis[j] = distance + w[i];
heap.push({dis[j], j});
}
}
}
if(dis[n] == 0x3f3f3f3f)
return -1;
return dis[n];
}
int main()
{
cin >> n >> m;
memset(h, -1 , sizeof h);
while(m--)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);//邻接表存储
}
cout << dijkstrea() << endl;
}