#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#define isr(A)	(s[s[A].fa].ch[0]!=A&&s[s[A].fa].ch[1]!=A)
using namespace std;
struct node
{
	int ch[2],fa,sm,v,rev;
}s[300010];
struct edge
{
	int px,py,pa,pb;
}p[200010];
int n,m,ans;
bool cmp(edge a,edge b)
{
	return a.pa<b.pa;
}
void pushup(int x)
{
	s[x].sm=s[s[x].ch[0]].sm;
	if(s[s[x].sm].v<s[s[s[x].ch[1]].sm].v)	s[x].sm=s[s[x].ch[1]].sm;
	if(s[s[x].sm].v<s[x].v)	s[x].sm=x;
}
void pushdown(int x)
{
	if(s[x].rev)
	{
		swap(s[x].ch[0],s[x].ch[1]);
		if(s[x].ch[0])	s[s[x].ch[0]].rev^=1;
		if(s[x].ch[1])	s[s[x].ch[1]].rev^=1;
		s[x].rev=0;
	}
}
void updata(int x)
{
	if(!isr(x))	updata(s[x].fa);
	pushdown(x);
}
void rotate(int x)
{
	int y=s[x].fa,z=s[y].fa,d=(x==s[y].ch[1]);
	if(!isr(y))	s[z].ch[y==s[z].ch[1]]=x;
	s[y].ch[d]=s[x].ch[d^1],s[x].fa=z,s[y].fa=x;
	if(s[x].ch[d^1])	s[s[x].ch[d^1]].fa=y;
	s[x].ch[d^1]=y;
	pushup(y),pushup(x);
}
void splay(int x)
{
	updata(x);
	while(!isr(x))
	{
		int y=s[x].fa,z=s[y].fa;
		if(!isr(y))
		{
			if((x==s[y].ch[0])^(y==s[z].ch[0]))	rotate(x);
			else	rotate(y);
		}
		rotate(x);
	}
}
void access(int x)
{
	int y=0;
	while(x)	splay(x),s[x].ch[1]=y,pushup(x),y=x,x=s[x].fa;
}
void maker(int x)
{
	access(x),splay(x),s[x].rev^=1;
}
void cut(int x,int y)
{
	maker(x),access(y),splay(y);
	s[x].fa=s[y].ch[0]=0,pushup(y);
}
void link(int x,int y)
{
	maker(y),s[y].fa=x;
}
int findr(int x)
{
	access(x),splay(x);
	while(s[x].ch[0])	x=s[x].ch[0];
	return x;
}
void split(int x,int y)
{
	maker(y),access(x),splay(x);
}
int rd()
{
	int ret=0;	char gc=getchar();
	while(gc<‘0‘||gc>‘9‘)	gc=getchar();
	while(gc>=‘0‘&&gc<=‘9‘)	ret=ret*10+gc-‘0‘,gc=getchar();
	return ret;
}
int main()
{
	n=rd(),m=rd();
	int i,a,b;
	for(i=1;i<=m;i++)	p[i].px=rd(),p[i].py=rd(),p[i].pa=rd(),p[i].pb=rd();
	sort(p+1,p+m+1,cmp);
	for(i=1;i<=n+m;i++)	s[i].sm=i;
	for(i=1;i<=m;i++)	s[i+n].v=p[i].pb;
	ans=1<<30;
	for(i=1;i<=m;i++)
	{
		if(findr(p[i].px)!=findr(p[i].py))	link(p[i].px,i+n),link(p[i].py,i+n);
		else
		{
			split(p[i].px,p[i].py);
			a=s[p[i].px].sm;
			if(s[a].v>p[i].pb)
			{
				cut(a,p[a-n].px),cut(a,p[a-n].py);
				link(p[i].px,i+n),link(p[i].py,i+n);
			}
		}
		if(findr(1)==findr(n))	split(1,n),ans=min(ans,p[i].pa+s[s[1].sm].v);
	}
	printf("%d",(ans==(1<<30))?-1:ans);
	return 0;
}