#include<bits/stdc++.h>
using namespace std;
const int N = 200000;
const int INF = 0x3f3f3f3f;
typedef pair<int,int> PII;
int n,m;
int h[N],w[N],e[N],ne[N],idx;
int dist[N];
bool vis[N];
void add(int u,int v,int c)
{
e[idx]=v,w[idx]=c,ne[idx]=h[u],h[u]=idx++;
}
int dijstria()
{
memset(dist,INF,sizeof dist);
priority_queue<PII , vector<PII> , greater<PII>> heap;
heap.push({0,1});
dist[1]=0;
while(heap.size())
{
auto t = heap.top();
heap.pop();
int distance = t.first,ver = t.second;
if(vis[ver]) continue;
vis[ver] = true;
for(int i=h[ver];i!=-1;i=ne[i])
{
int j=e[i];
if(dist[j] > distance + w[i])
{
dist[j] = distance + w[i];
heap.push({dist[j],j});
}
}
}
if(dist[n]==INF) return -1;
else return dist[n];
}
int main()
{
cin>>n>>m;
memset(h,-1,sizeof h);
for(int i=0;i<m;++i)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
cout<<dijstria()<<endl;
return 0;
}