#include <cstdlib>
#include <iostream>
#include<string>
#include<algorithm>
#include<math.h>
#include<queue>
using namespace std;
queue <int>q;
const int MAXN=150010;
const int INF=19950420;int kk;
int first[MAXN],u[MAXN],v[MAXN],w[MAXN],next[MAXN];
int d[MAXN]={0};int inq[MAXN]={0};int n,m;
void spfa(int st)
{
q.push(st);
for(int i=1;i<=n;i++)d[i]=i==st?0:INF;
inq[st]=1;
while(!q.empty())
{
int x=q.front();
q.pop();
inq[x]=0;
for(int i=first[x];i!=-1;i=next[i])
{
if(d[x]+w[i]<d[v[i]])
{
d[v[i]]=d[x]+w[i];
if(!inq[v[i]])
{
inq[v[i]]=1;
q.push(v[i]);
}
}
}
}
}
void init()
{
cin>>n>>m;
for(int i=1;i<=n;i++)first[i]=-1;
for(int i=1;i<=m;i++)
{
scanf("%d %d %d",&u[i],&v[i],&w[i]);
next[i]=first[u[i]];
first[u[i]]=i;
first[v[i]]=i;
}
}
int main(int argc, char *argv[])
{//freopen("a.in","r",stdin);
//freopen("a.out","w",stdout);
init();
spfa(1);
//for(int i=1;i<=n;i++)cout<<d[i]<<" ";
//cout<<endl;
if(d[n]!=INF)cout<<d[n];
else cout<<-1;
//system("PAUSE");
return EXIT_SUCCESS;
}
#include <iostream>
#include<string>
#include<algorithm>
#include<math.h>
#include<queue>
using namespace std;
queue <int>q;
const int MAXN=150010;
const int INF=19950420;int kk;
int first[MAXN],u[MAXN],v[MAXN],w[MAXN],next[MAXN];
int d[MAXN]={0};int inq[MAXN]={0};int n,m;
void spfa(int st)
{
q.push(st);
for(int i=1;i<=n;i++)d[i]=i==st?0:INF;
inq[st]=1;
while(!q.empty())
{
int x=q.front();
q.pop();
inq[x]=0;
for(int i=first[x];i!=-1;i=next[i])
{
if(d[x]+w[i]<d[v[i]])
{
d[v[i]]=d[x]+w[i];
if(!inq[v[i]])
{
inq[v[i]]=1;
q.push(v[i]);
}
}
}
}
}
void init()
{
cin>>n>>m;
for(int i=1;i<=n;i++)first[i]=-1;
for(int i=1;i<=m;i++)
{
scanf("%d %d %d",&u[i],&v[i],&w[i]);
next[i]=first[u[i]];
first[u[i]]=i;
first[v[i]]=i;
}
}
int main(int argc, char *argv[])
{//freopen("a.in","r",stdin);
//freopen("a.out","w",stdout);
init();
spfa(1);
//for(int i=1;i<=n;i++)cout<<d[i]<<" ";
//cout<<endl;
if(d[n]!=INF)cout<<d[n];
else cout<<-1;
//system("PAUSE");
return EXIT_SUCCESS;
}