给定一个 nn 个点 mm 条边的有向图,图中可能存在重边和自环,所有边权均为非负值。
请你求出 11 号点到 nn 号点的最短距离,如果无法从 11 号点走到 nn 号点,则输出 −1−1。
输入格式
第一行包含整数 nn 和 mm。
接下来 mm 行每行包含三个整数 x,y,zx,y,z,表示存在一条从点 xx 到点 yy 的有向边,边长为 zz。
输出格式
输出一个整数,表示 11 号点到 nn 号点的最短距离。
如果路径不存在,则输出 −1−1。
数据范围
1≤n,m≤1.5×1051≤n,m≤1.5×105,
图中涉及边长均不小于 00,且不超过 1000010000。
数据保证:如果最短路存在,则最短路的长度不超过 109109。输入样例:
3 3 1 2 2 2 3 1 1 3 4
输出样例:
3
#include<iostream>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;
struct edge{
int to;
int cost;
};
typedef pair<int, int> P; //first is shortest distance, second is the number of vertex
int n, m;
const int MAX_V = 1.5e5 + 10;
const int INF = 0x3f3f3f3f;
vector<edge> G[MAX_V];
int d[MAX_V]; // shortest distance
void dijkstra(int s)
{
priority_queue<P, vector<P>, greater<P> > que; // greater<P> is from small to large, less<P> is reverse;
fill(d, d + MAX_V, INF);
d[s] = 0;
que.push(P(0, s));
while(!que.empty())
{
P p = que.top();
que.pop();
int v = p.second;
if(d[v] < p.first) continue;
for(int i = 0; i < G[v].size(); i ++){
edge e = G[v][i];
if(d[e.to] > d[v] + e.cost){
d[e.to] = d[v] + e.cost;
que.push(P(d[e.to], e.to));
}
}
}
if(d[n] >= INF) cout<< -1;
else cout<<d[n];
}
int main()
{
ios::sync_with_stdio(false);
cout.tie(NULL);
cin >> n >> m;
for(int i = 1;i <= n;i ++){
G[i].clear();
}
for(int i = 1; i <= m; i ++){
int x, y, z;
cin >> x >> y >> z;
edge temp;
temp.to = y;
temp.cost = z;
G[x].push_back(temp);
}
dijkstra(1);
return 0;
}