/*
Problem F: 地铁
Time Limit: 5 Sec Memory Limit: 128 MB
Submit: 84 Solved: 8
[Submit][Status][Web Board]
Description
Bobo 居住在大城市 ICPCCamp。
ICPCCamp 有 n 个地铁站,用 1,2,…,n 编号。 m 段双向的地铁线路连接 n 个地铁站,其中第 i 段地铁属于 ci 号线,位于站 ai,bi 之间,往返均需要花费 ti 分钟(即从 ai 到 bi 需要 ti 分钟,从 bi 到 ai 也需要 ti 分钟)。
众所周知,换乘线路很麻烦。如果乘坐第 i 段地铁来到地铁站 s,又乘坐第 j 段地铁离开地铁站 s,那么需要额外花费 |ci-cj | 分钟。注意,换乘只能在地铁站内进行。
Bobo 想知道从地铁站 1 到地铁站 n 所需要花费的最小时间。
Input
输入包含不超过 20 组数据。
每组数据的第一行包含两个整数 n,m (2≤n≤105,1≤m≤105).
接下来 m 行的第 i 行包含四个整数 ai,bi,ci,ti (1≤ai,bi,ci≤n,1≤ti≤109).
保证存在从地铁站 1 到 n 的地铁线路(不一定直达)。
Output
对于每组数据,输出一个整数表示要求的值。
Sample Input
3 3
1 2 1 1
2 3 2 1
1 3 1 1
3 3
1 2 1 1
2 3 2 1
1 3 1 10
3 2
1 2 1 1
2 3 1 1
Sample Output
1
3
2
*/
/*
题目:地铁
题意:给出一个无向图G,顶点1~n,m条边,每条边有一个cost和一个value,从一条边到另外一条边(假设i->j)
要外加abs(i,j)的耗费,问从顶点1->n 最小耗费.
思路:显然这道题与普通最短路的区别在与换路的耗费,如果用普通最短路做法更新顶点的最短距离的话,
会丢失那些到达某个顶点不是最优解但经过换路后可以成为最优解的情况.
但是换个思路,如果我们每次更新的不是到达顶点的最短路而是到达某条边的最短路的话(也就是确定
了接下来只能走那条边),就变成普通的最短路了,这样可以用各种nlogn的算法解决;详见代码:
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <iostream>
using namespace std;
struct edge
{
int to,e,c,t;//分别代表边的终点,编号,value,cost;
edge(int to,int e,int c,int t):to(to),e(e),c(c),t(t){}
};
int const maxn=1e5+100;
typedef long long LL;
const LL INF=1e14;
vector<edge> G[maxn];
LL dis[maxn<<1];
int n,m;
struct node
{
edge e;//记录下一步是走那条边
LL dis;//刚踏上这条边时所需最短路
node(edge e,LL d):e(e),dis(d){}
bool operator <(const node& a)const{
return dis > a.dis;
}
};
priority_queue<node> que;
void init()
{
for (int i=1;i<=n;i++){
G[i].clear();
}
for (int i=1;i<=m*2;i++){
dis[i]=INF;
}
while (!que.empty()) que.pop();
}
LL dijkstra()
{
for (int i=0;i<(int)G[1].size();i++){
edge &e=G[1][i];
dis[e.e]=0;//初始化,把所有一开始就算到达的边初始化
que.push(node(e,0));
}
LL mi=INF;
while (!que.empty())
{
node nd=que.top();que.pop();
if (dis[nd.e.e]<nd.dis) continue;//已被其它路径更新,次node无用
if (nd.e.to==n){ if (nd.dis+nd.e.t<mi) mi=nd.dis+nd.e.t;}//找到一解,比较取优
for (int i=0;i<(int)G[nd.e.to].size();i++){
edge &e=G[nd.e.to][i];
if(dis[nd.e.e]+nd.e.t+abs(e.c-nd.e.c) < dis[e.e]){//往下条边更新
dis[e.e]=dis[nd.e.e]+nd.e.t+abs(e.c-nd.e.c);
que.push(node(e,dis[e.e]));
}
}
}
return mi;
}
int main()
{
//freopen("D:in.txt","r",stdin);
while (scanf("%d%d",&n,&m)==2)
{
init();
for (int i=1;i<=m;i++){
int a,b,c,t;
scanf("%d%d%d%d",&a,&b,&c,&t);
G[a].push_back(edge(b,i,c,t));
G[b].push_back(edge(a,i+m,c,t));//编号1~2*m
}
cout<<dijkstra()<<endl;
}
return 0;
}