堆优化版dijkstra算法

1.堆优化版dijkstra算法模板

时间复杂度 O(mlogn), n 表示点数,m 表示边数

typedef pair<int, int> PII;

int n;      // 点的数量
int h[N], w[N], e[N], ne[N], idx;       // 邻接表存储所有边
int dist[N];        // 存储所有点到1号点的距离
bool st[N];     // 存储每个点的最短距离是否已确定

// 求1号点到n号点的最短距离,如果不存在,则返回-1
int dijkstra()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    priority_queue<PII, vector<PII>, greater<PII>> heap;
    heap.push({0, 1});      // first存储距离,second存储节点编号

    while (heap.size())
    {
        auto t = heap.top();
        heap.pop();

        int ver = t.second, distance = t.first;

        if (st[ver]) continue;
        st[ver] = true;

        for (int i = h[ver]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > distance + w[i])
            {
                dist[j] = distance + w[i];
                heap.push({dist[j], j});
            }
        }
    }

    if (dist[n] == 0x3f3f3f3f) return -1;
    return dist[n];
}

2.示例

给定一个n个点m条边的有向图,图中可能存在重边和自环,所有边权均为非负值。

请你求出1号点到n号点的最短距离,如果无法从1号点走到n号点,则输出-1。

输入格式

第一行包含整数n和m。
接下来m行每行包含三个整数x,y,z,表示存在一条从点x到点y的有向边,边长为z。

输出格式

输出一个整数,表示1号点到n号点的最短距离。
如果路径不存在,则输出-1。
数据范围1≤n,m≤1.5×105,图中涉及边长均不小于0,且不超过10000。

输入样例:

3 3
1 2 2
2 3 1
1 3 4

输出样例:

3

代码:

#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>

#define MAX 0x3f3f3f3f

using namespace std;

typedef pair<int, int> PII;
const int N = 150010;

int h[N], w[N], e[N], ne[N], idx;       // 邻接表存储所有边
int dis[N];		//每个点到起点的距离
bool st[N];		//该点最短距离是否已经确定
int n, m;

void add(int a, int b, int c)
{
	/* 有重边也不要紧,假设1->2有权重为2和3的边,再遍历到点1的时候2号点的距离会更新两次放入堆中,
	这样堆中会有很多冗余的点,但是在弹出的时候还是会弹出最小值2+x(x为之前确定的最短路径),
	并标记st为true,所以下一次弹出3+x会continue不会向下执行。*/
	w[idx] = c;
	e[idx] = b;
	ne[idx] = h[a];
	h[a] = idx++;
}

// 求1号点到n号点的最短距离,如果不存在,则返回-1
int dijkstra()
{
	memset(dis, MAX, sizeof dis);
	dis[0] = 1;	

	//创建小根堆
	priority_queue<PII, vector<PII>, greater<PII>> heap;
	heap.push({ 0, 1 });	//first为距离,second为节点编号

	while (heap.size()) {
		auto it = heap.top();
		heap.pop();

		int distance = it.first, val = it.second;
		if (st[val])
			continue;

		st[val] = true;
		for (int i = h[val]; i != -1; i = ne[i]) {
			int j = e[i];
			if (distance + w[i] < dis[j]) {
				dis[j] = distance + w[i];
				heap.push({ dis[j],j });
			}
		}
	}

	if (dis[n] == MAX)
		return -1;

	return dis[n];
}

int main()
{
	memset(h, -1, sizeof h);

	//input
	cin >> n >> m;

	//process
	int x, y, z;
	for (int i = 0; i < m; i++)
	{
		cin >> x >> y >> z;
		add(x, y, z);
	}

	//output
	cout << dijkstra() << endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43202635/article/details/107491884
今日推荐