#pragma GCC optimization O2
#pragma GCC optimization "unroll-loop"
#pragma target ("avx2")
#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define fs first
#define sc second
using namespace std;
typedef pair<ll,ll> LL;
const ll N = 1e5 + 9;
const ll Log2 = 20;
const ll inf = 1e16 + 7;
map<LL,ll> mp,All;
vector<ll> d[N][2];
ll n,m,x,y,c,p,ans = inf;
struct Edge{
ll to,c,p;
};
vector<Edge> g[N];
struct Node{
ll val,i,prv,change;
};
bool operator < (Node a,Node b){
return a.val > b.val;
}
priority_queue<Node> pq;
int main(){
ios_base::sync_with_stdio(NULL); cin.tie(0); cout.tie(0);
#define task "tst"
if (fopen(task".INP","r")){
freopen(task".INP","r",stdin);
//freopen(task".OUT","w",stdout);
}
cin>>n>>m;
while(m--){
cin>>x>>y>>c>>p;
mp[{x,y}] = g[x].size(); mp[{y,x}] = g[y].size();
g[x].push_back({y,c,p}); g[y].push_back({x,c,p});
}
for (ll i = 1;i <= n;i++){
d[i][0].resize(g[i].size() + 3); d[i][1].resize(g[i].size() + 3);
for (ll j = 0;j < d[i][0].size();j++){
d[i][0][j] = d[i][1][j] = inf;
if (i == 1) d[i][0][j] = d[i][1][j] = 0;
}
for (auto j : g[i]) All[{i,j.c}] += j.p;
}
pq.push({0,1,inf,0});
while(!pq.empty()){
//cout<<"?";
Node t = pq.top(); pq.pop();
ll u = t.i;
if (u == n){
ans = min(ans,t.val);
}
for (ll i = 0;i < g[u].size();i++){
if (i == t.prv) continue;
ll curC = g[u][i].c,v = g[u][i].to,L = g[u][i].p,change;
ll cost = All[{u,curC}] - L;
if (t.prv != inf && g[u][i].c == g[u][t.prv].c && t.change)
cost -= g[u][t.prv].p;
change = (L <= cost); cost = min(cost,L);
assert(t.change <= 1); assert(cost >= 0);
ll id = mp[{v,u}];
if (d[v][change][id] > t.val + cost){
d[v][change][id] = t.val + cost;
pq.push({t.val + cost,v,id,change});
}
}
}
if (ans != inf) cout<<ans;
else cout<<-1;
}