B3602 [图论与代数结构 202] 最短路问题_2
https://www.luogu.com.cn/problem/B3602
#include<iostream>
#include<cstdio>
#include<queue>
#include<limits.h>
using namespace std;
using ll = long long;
ll m, n, head[300005], a, b, c, all;//记录每个点对应边的起点位置
bool vis[300005];//记录已经确定了最短长度的点
ll dis[300005]; //记录当前最短路径长度
struct edge{
ll next, to, w;//next这个点的下一条边是哪一条,to 指向那条边, 边的权重是多少;
}E[300005];//记录边的情况
void add()//构建链式存边
{
all++;
E[all].next = head[a];
E[all].to = b;
E[all].w = c;
head[a] = all;
}
struct tt {//仿函数,修改优先队列的排序
bool operator()(pair<ll, ll> a, pair<ll, ll> b)
{
return a.first > b.first;
}
};
priority_queue<pair<ll,ll>,vector<pair<ll,ll>>,tt>p;//first 记录最短长度,second 记录是那个点
void ds(int k)//寻找最短路径
{
for (int i = 1; i <= m; ++i) {
dis[i] = LLONG_MAX;
}
p.push({ 0,k });
while (!p.empty()) {
pair<ll,ll> t = p.top();
p.pop();
if (vis[t.second])continue;//同一个点可能更新多次,可能被放入队列多次,我们只确定最短的,其余直接跳过。
dis[t.second] = t.first;
vis[t.second] = 1;//标记该点已经确定,不用再往队列中放;
for (ll i = head[t.second]; i; i = E[i].next) {
if (t.first + E[i].w < dis[E[i].to]) {
dis[E[i].to] = t.first + E[i].w;
if (!vis[E[i].to]) {
p.push({ dis[E[i].to],E[i].to });
}
}
}
}
}
int main()
{
cin >> m >> n;
for (int i = 1; i <= n; ++i) {
cin >> a >> b >> c;
add();
}
ds(1);
for (int i = 1; i <= m; ++i) {
printf("%ld ", dis[i] == LLONG_MAX ? -1 : dis[i] );
}
return 0;
}