dijkstra模板

dijkstra算法用于求无负权边的最短路题型

dijkstra朴素做法, 适用于节点数较少的稠密图,时间复杂度为O(n^2)

#include <bits/stdc++.h>
using namespace std;
const int N = 510, M = 100010;

int e[M], w[M], ne[M], h[N], idx;
int dist[N];
bool st[N]; 
int n, m;

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

void dijkstra()
{
	memset(dist, 0x3f, sizeof dist);
	memset(st, false, sizeof st);
	dist[1] = 0;
	for (int k = 0; k < n; k ++ )
	{
		int t = -1;
		for (int j = 1; j <= n; j ++)
			if (!st[j] && (t == -1 || dist[j] < dist[t])) t = j;
		st[t] = true;
		for (int i = h[t]; ~i; i = ne[i] )
		{
			int j = e[i];
			if (dist[j] > dist[t] + w[i] ) dist[j] = dist[t] + w[i];
		} 
 	}
}

int main()
{
	memset(h, -1, sizeof h);
	cin >> n >> m;
	for (int i = 0; i < m; i ++ )
	{
		int a, b, c;
		cin >> a >> b >> c;
		add(a, b, c);
	}
	dijkstra();
	if (dist[n] == 0x3f3f3f3f) dist[n] = -1;
	cout << dist[n];
	return 0;
}

dijkstra堆优化,时间复杂度为O(mlongn),适用于稀疏图,当求解的图是稠密图时,其效率一般都不如朴素的dijkstra

#include <bits/stdc++.h>
#define x first
#define y second
using namespace std;
const int N = 150010, M = 150010;
typedef pair<int, int> PII;
int e[M], w[M], ne[M], h[N], idx;
int dist[N];
bool st[N]; 
int n, m;

void add(int a, int b, int c) // 邻接表加边
{
	e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}

void dijkstra()
{
	priority_queue<PII, vector<PII>, greater<PII> > heap;
	memset(dist, 0x3f, sizeof dist);
	memset(st, false, sizeof st);
	dist[1] = 0;
	heap.push({0, 1});
	while (heap.size())
	{
		PII a = heap.top();
		heap.pop();
		int u = a.y;
		if (st[u]) continue;
		st[u] = true;
		for (int i = h[u]; ~i; i = ne[i] )
		{
			int j = e[i];
			if (dist[j] > dist[u] + w[i])
			{
				dist[j] = dist[u] + w[i];
				heap.push({dist[j], j});
			} 
		}
	}
}

int main()
{
	memset(h, -1, sizeof h);
	cin >> n >> m;
	for (int i = 0; i < m; i ++ )
	{
		int a, b, c;
		cin >> a >> b >> c;
		add(a, b, c);
	}
	dijkstra();
	if (dist[n] == 0x3f3f3f3f) dist[n] = -1; // 从起点抵达不了终点
	cout << dist[n];
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值