#include<bits/stdc++.h>
#define NMAX 200005
#define LOG 20
#define ll long long int
#define MOD 998244353
#define BASE 32
#define INF (ll)1e17
#define VMAX 30000
using namespace std;
ifstream fin("cod.in");
ofstream fout("cod.out");
struct edge
{
int y,c,p,id;
};
int ec[NMAX+1],ep[NMAX+1];
struct state
{
int x,e;
ll d;
state (){};
state (int x,int e, ll d) : x(x) , e(e) , d(d){};
bool operator<(state &oth)
{
return this->d > oth.d;
}
};
vector<edge> adj[NMAX+1];
int n,m;
unordered_map<int,ll> dist[NMAX+1],sump[NMAX+1];
unordered_map<int,int> cnt[NMAX+1];
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cin >> n >> m;
for(int i=1;i<=m;i++)
{
int a,b,c,p;
cin >> a >> b >> c >> p;
adj[a].push_back({b,c,p,i});
adj[b].push_back({a,c,p,i});
ec[i] = c;
ep[i] = p;
}
for(int i=1;i<=n;i++)
{
dist[i][0] = 1e17;
for(auto e : adj[i])
{
dist[i][e.id] = 1e17;
sump[i][e.c] += e.p;
cnt[i][e.c]++;
}
}
vector<state> pq;
pq.push_back({1,0,0});
make_heap(pq.begin(),pq.end());
dist[1][0] = 0;
while(!pq.empty())
{
pop_heap(pq.begin(),pq.end());
int x = pq.back().x;
int e = pq.back().e;
ll d = pq.back().d;
pq.pop_back();
if(dist[x][e] < d)
{
continue;
}
for(auto [y,c,p,id] : adj[x])
{
if(id==e)
{
continue;
}
ll cost = sump[x][c] - p;
if(ec[e] == c)
{
cost -= ep[e];
}
if(dist[y][0] > dist[x][e] + cost)
{
dist[y][0] = dist[x][e] + cost;
pq.push_back({y,0,dist[y][0]});
push_heap(pq.begin(),pq.end());
}
if(dist[y][id] > dist[x][e] + p)
{
dist[y][id] = dist[x][e] + p;
pq.push_back({y,id,dist[y][id]});
push_heap(pq.begin(),pq.end());
}
}
}
ll res = 1e17;
for(auto [id,d] : dist[n])
{
res = min(d, res);
}
if(res == 1e17)
{
res = -1;
}
cout << res << '\n';
}