Description
Bobo 居住在大城市 ICPCCamp。
ICPCCamp 有 n 个地铁站,用 1,2,…,n 编号。 m 段双向的地铁线路连接 n 个地铁站,其中第 i 段地铁属于 c
i 号线,位于站 a
i,b
i 之间,往返均需要花费 t
i 分钟(即从 a
i 到 b
i 需要 t
i 分钟,从 b
i 到 a
i 也需要 t
i 分钟)。
众所周知,换乘线路很麻烦。如果乘坐第 i 段地铁来到地铁站 s,又乘坐第 j 段地铁离开地铁站 s,那么需要额外花费 |c
i-c
j | 分钟。注意,换乘只能在地铁站内进行。
Bobo 想知道从地铁站 1 到地铁站 n 所需要花费的最小时间。
Input
输入包含不超过 20 组数据。
每组数据的第一行包含两个整数 n,m (2≤n≤10
5,1≤m≤10
5).
接下来 m 行的第 i 行包含四个整数 a
i,b
i,c
i,t
i (1≤a
i,b
i,c
i≤n,1≤t
i≤10
9).
保证存在从地铁站 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
代码:
#include <cstdio>
#include <queue>
#include <cmath>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAX 100005
#define LL long long
using namespace std;
const int INF = 0x3f3f3f3f;
inline void RI(int &x)
{
char c;
while((c=getchar())<'0' || c>'9');
x=c-'0';
while((c=getchar())>='0' && c<='9') x=(x<<3)+(x<<1)+c-'0';
}
struct Edge
{
int v, next, num, c;
}edge[MAX*2];
struct Node
{
int id, val;
bool operator<(const Node &a)const{
return val > a.val;
}
}x;
int head[MAX], vis[MAX*2], tot;
LL dis[MAX*2];
void add_edge(int a, int b, int c, int d)
{
edge[tot] = (Edge){b, head[a], c, d};
head[a] = tot++;
edge[tot]=(Edge){a, head[b], c, d};
head[b] = tot++;
}
LL dijkstra(int s,int t)
{
priority_queue<Node> Q;
for(int i = 0; i < tot; i++)
{
dis[i] = 1e18;
vis[i] = 0;
}
for(int i = head[s]; i != -1; i = edge[i].next){
x = (Node){i, edge[i].c};
dis[i] = edge[i].c;
Q.push(x);
}
LL ans = 1e18;
while(!Q.empty())
{
x = Q.top();
Q.pop();
int p = x.id;
if(vis[p]) continue;
vis[p] = 1;
int u = edge[p].v;
if(u == t) ans = min(ans,dis[p]);
for(int i = head[u]; i != -1; i = edge[i].next)
{
int v = edge[i].v;
if(!vis[i] && dis[i] > dis[p] + edge[i].c + abs(edge[i].num - edge[p].num))
{
dis[i] = dis[p] + edge[i].c + abs(edge[i].num-edge[p].num);
Q.push((Node){i, dis[i]});
}
}
}
return ans;
}
int main()
{
int n, m, a, b, c, d;
while(scanf("%d%d", &n, &m) != EOF)
{
tot = 0;
for(int i = 1; i <= n; i++) head[i] = -1;
for(int i = 0; i < m; i++)
{
scanf("%d%d%d%d", &a, &b, &c, &d);
add_edge(a, b, c, d);
}
printf("%lld\n", dijkstra(1,n));
}
return 0;
}