稀疏图的Djikstra(堆优化 通用)

题目

//堆优化版
#include <bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
#define fi first
#define se second
#define endl '\n'
#define IOS std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
using namespace std;

const int N = 5e5 + 10;

int h[N], ne[N], e[N], w[N], bj[N], dis[N], idx;
int n,m;

void add(int a, int b, int c)
{
	e[idx] = b;
	w[idx] = c;
	ne[idx] = h[a];
	h[a] = idx ++;
}

struct node
{
	friend bool operator < (node a, node b)
	{
		return a.cost > b.cost;  //记得>是小顶堆,<是大顶堆
	}
	int to;
	int cost;
};

bool dji()
{
	priority_queue<node> Q;
	node head;
	head.cost = 0;
	head.to = 1;
	dis[1] = 0;
	Q.push(head);
	while(Q.size())
	{
		node now = Q.top();
		Q.pop();
		if(bj[now.to]) continue;
		bj[now.to] = 1;
		for(int j = h[now.to]; ~j; j = ne[j]) //遍历所有从now.to出发的边
		{
			int x = e[j];
			if(dis[x] > now.cost + w[j])  //松弛
			{
				node next;
				dis[x] = now.cost + w[j];
				next.cost = dis[x];
				next.to = x;
				Q.push(next);
			}
		}
	}
	return dis[n] == inf;
}

int main()
{
	memset(h, -1, sizeof h);  //初始化
	memset(dis, inf, sizeof dis); 
	cin >> n >> m;
	while(m --)
	{
		int a, b, c;
		cin >> a >> b >> c;
		add(a, b, c);
		add(b, a, c);
	}
	if(dji())
		cout << "qwb baka" << endl;
	else
		cout << dis[n];
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值