#include<iostream>
#include<queue>
#include<algorithm>
#include<cstring>
using namespace std;
const int N=1e6+10;
typedef pair<int ,int> PII;
int h[N],w[N],e[N],ne[N],n,m,idx;
bool st[N];
int dist[N];
void add(int x,int y,int z){
e[idx]=y,ne[idx]=h[x],w[idx]=z,h[x]=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()){
PII t=heap.top();
heap.pop();
if(st[t.second]) continue;
st[t.second]=true;
for(int i=h[t.second];i!=-1;i=ne[i]){
int j=e[i];
if(dist[j]>dist[t.second]+w[i]){
dist[j]=dist[t.second]+w[i];
heap.push({dist[j],j});
}
}
}
if(dist[n]==0x3f3f3f3f) return -1;
return dist[n];
}
int main(){
cin>>n>>m;
memset(h,-1,sizeof h);
while(m--){
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
}
cout<<dijkstra()<<endl;
return 0;
}