Dijkstra算法模板 C++

代码出自:《算法竞赛入门经典——训练指南》P328

#include<iostream>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 10005;
const int INF = 2147483647;
struct Edge{
	int from,to,dist;
};
struct HeapNode{
	int d,u;
	bool operator <(const HeapNode & a) const{
		return d > a.d;
	}
};
struct Dijkstra{
	int n,m;
	vector<Edge> edges;
	vector<int> G[maxn]; 
	int d[maxn];
	bool vis[maxn];
	int p[maxn];
	
	void init(int n){
		this->n = n;
		for(int i = 0;i <= n;i++)	G[i].clear();
		memset(vis,false,sizeof vis);
		for(int i = 0;i <= n;i++)	p[i] = i;
		for(int i = 1;i <= n;i++)	d[i] = INF;
	}
	void add_edge(int from,int to,int dist){
		edges.push_back(Edge{from,to,dist});
		m = edges.size();
		G[from].push_back(m-1);
	}
	void dijkstra(int s){
		priority_queue<HeapNode> q;
		q.push(HeapNode{0,s});
		d[s] = 0;
		while(!q.empty()){
			HeapNode x = q.top();
			q.pop();
			int u = x.u;
			if(vis[u])	continue;
			vis[u] = true;
			for(int i = 0;i < G[u].size();i++){
				Edge& e = edges[G[u][i]];
				if(d[e.to] > d[u] + e.dist){
					d[e.to] = d[u] + e.dist;
					p[e.to] = u;
					q.push(HeapNode{d[e.to],e.to});
				}
			}
		}
	}
};

 

    原文作者:Dijkstra算法
    原文地址: https://blog.csdn.net/weixin_41162823/article/details/82018867
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞