1 #include<cstdio>
2 #include<cstdlib>
3 #include<cstring>
4 #include<iostream>
5 #include<algorithm>
6 #include<queue>
7 using namespace std;
8 #define Maxn 50010
9 #define Maxm 100010
10 #define INF 0x7fffffff
11
12 int mymax(int x,int y) {return x>y?x:y;}
13 int mymin(int x,int y) {return x<y?x:y;}
14
15 struct node
16 {
17 int x,y,a,b,next;
18 };
19 node t[Maxm*2],eg[Maxm];
20 int first[Maxn],len;
21
22 void ins(int x,int y,int a,int b)
23 {
24 t[++len].x=x;t[len].y=y;t[len].a=a;t[len].b=b;
25 t[len].next=first[x];first[x]=len;
26 }
27
28 bool cmp(node x,node y) {return x.a<y.a;}
29
30 int dis[Maxn];
31 bool inq[Maxn];
32 queue<int > q;
33
34 int st,ed;
35 void spfa()
36 {
37 while(!q.empty())
38 {
39 int x=q.front();
40 for(int i=first[x];i;i=t[i].next)
41 {
42 int y=t[i].y;
43 if(dis[y]>mymax(dis[x],t[i].b))
44 {
45 dis[y]=mymax(dis[x],t[i].b);
46 if(!inq[y])
47 {
48 inq[y]=1;
49 q.push(y);
50 }
51 }
52 }
53 inq[x]=0;q.pop();
54 }
55 }
56
57 int main()
58 {
59 int n,m;
60 scanf("%d%d",&n,&m);
61 for(int i=1;i<=m;i++)
62 {
63 scanf("%d%d%d%d",&eg[i].x,&eg[i].y,&eg[i].a,&eg[i].b);
64 }
65 sort(eg+1,eg+1+m,cmp);
66 st=1;ed=n;
67 while(!q.empty()) q.pop();
68 memset(dis,63,sizeof(dis));
69 memset(inq,0,sizeof(inq));
70 dis[st]=0;inq[st]=1;q.push(st);
71 len=0;
72 int ans=INF;
73 for(int i=1;i<=m;i++)
74 {
75 ins(eg[i].x,eg[i].y,eg[i].a,eg[i].b);
76 ins(eg[i].y,eg[i].x,eg[i].a,eg[i].b);
77 q.push(eg[i].x);q.push(eg[i].y);
78 inq[eg[i].x]=inq[eg[i].y]=1;
79 spfa();
80 if(dis[ed]<10000000) ans=mymin(ans,eg[i].a+dis[ed]);
81 }
82 if(ans>1000000) ans=-1;
83 printf("%d\n",ans);
84 return 0;
85 }