#include<bits/stdc++.h>
#define x first
#define y second
using namespace std;
typedef pair<int,int>PII;
const int N=150010;
int n,m;
int h[N],e[N],w[N],ne[N],idx;
int d[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 dijksra()
{
memset(d,0x3f,sizeof d);
d[1]=0;
priority_queue<PII,vector<PII>,greater<PII>>heap;
heap.push({0,1});
while(heap.size())
{
auto t=heap.top();heap.pop();
int dd=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(d[j]>dd+w[i])
{
d[j]=dd+w[i];
heap.push({d[j],j});
}
}
}
if(d[n]==0x3f3f3f3f)return -1;
return d[n];
}
int main()
{
std::ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>n>>m;
memset(h,-1,sizeof h);
while(m--)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
cout<<dijksra()<<endl;
return 0;
}