2021-8-13 链式存(图)边,Dijkstra最短路径

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值