#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N = 150010;
int h[N],e[N],ne[N],w[N],idx; //dist,st里装的是真正编号,w里装的是索引
int dist[N];
bool st[N];
int n,m;
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);
priority_queue<PII,vector<PII>,greater<PII>> q;
q.push({0,1});
dist[1]=0;
while(q.size())
{
PII t=q.top();
q.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];
q.push({dist[j],j});
}
}
}
return dist[n];
}
int main()
{
memset(h,-1,sizeof h);
cin>>n>>m;
while(m--)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
}
int res=dijkstra();
if(res==0x3f3f3f3f)
{
cout<<"-1";
return 0;
}
else cout<<res;
}