堆优化的dijkstra(迪杰斯特拉)

前面在讲prim算法的时候已经提到了dijkstra,这里再说说求最短路的dijkstra算法;

相比于邻接矩阵的存图方式我们可以用更适用于做题的链式前向星,更省空间;

我们也可以用STL的priority_queue优先队列进行优化(手写堆太麻烦了~~)

下面看代码(写的是求各个点到其他各个点的最短距离,可以用来当模板)

#include<cmath>
#include<queue>//优先队列是队列的一种
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=100010;
int to[maxn],m,bi[maxn],ne[maxn],ww[maxn],e,p[maxn],dis[maxn];
struct node{
	int hao,w;
};
bool operator <(node a,node b){
	return (a.w>b.w);//这样重载运算符写的是小根堆
}
struct dj{
	void init(){//初始化
		memset(p,0,sizeof(p));
		memset(dis,0,sizeof(dis));
		e=0;
	}
	void add(int x,int y,int z){//链式前向星存图
		to[++e]=y;
		ne[e]=bi[x];
		bi[x]=e;
		ww[e]=z;
	}
	void dijie(int h){
		for(int i=1;i<=m;i++)dis[i]=999999999;
		priority_queue<node>o;//定义一个node形的优先队列
		dis[h]=0;
		o.push((node){h,0});
		while(!o.empty()){
			node flag=o.top();
			o.pop();
			int u=flag.hao;
			if(p[u])continue;
			int v=flag.w;
			p[u]=1;
			dis[u]=v;
			for(int i=bi[u];i;i=ne[i]){
				int t=to[i];
				if(dis[t]>dis[u]+ww[i])
				dis[t]=dis[u]+ww[i];
				o.push((node){t,dis[t]});
			}
		}
	}
	void out(){
		for(int i=1;i<=m;i++)printf("%d ",dis[i]);
	}
}s;
int main(){
	int i,j,k,n,x,y,z;
	scanf("%d%d",&m,&n);
	for(i=1;i<=n;i++){
		scanf("%d%d%d",&x,&y,&z);
		s.add(x,y,z);
		s.add(y,x,z);
	}
	for(i=1;i<=m;i++){ 
	s.dijie(i);
	s.out();
	printf("\n");
	s.init();
}
 return 0;
}


  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 以下是使用堆优化斯特最短路算法的代码实现,代码中使用了一个优先队列来维护待处理的节点。 ``` #include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; const int MAXN = 100005; struct Edge { int to, w; Edge(int t, int weight) : to(t), w(weight) {} }; vector<Edge> G[MAXN]; int dist[MAXN]; bool vis[MAXN]; void dijkstra(int s) { memset(dist, INF, sizeof(dist)); memset(vis, 0, sizeof(vis)); priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q; dist[s] = 0; q.push({dist[s], s}); while (!q.empty()) { int u = q.top().second; q.pop(); if (vis[u]) continue; vis[u] = true; for (auto& e : G[u]) { int v = e.to, w = e.w; if (dist[v] > dist[u] + w) { dist[v] = dist[u] + w; if (!vis[v]) { q.push({dist[v], v}); } } } } } int main() { int n, m, s; scanf("%d%d%d", &n, &m, &s); for (int i = 1; i <= m; ++i) { int u, v, w; scanf("%d%d%d", &u, &v, &w); G[u].emplace_back(v, w); } dijkstra(s); for (int i = 1; i <= n; ++i) { if (dist[i] == INF) { printf("INF "); } else { printf("%d ", dist[i]); } } return 0; } ``` 这段代码实现了堆优化斯特最短路算法,可以处理有向图和无向图中单源最短路径问题。 ### 回答2: #include <iostream> #include <vector> #include <queue> #include <limits> using namespace std; struct Edge { int to; int weight; }; // 定义优先队列的比较规则,按照边的权重大小进行排序 struct cmp { bool operator()(const Edge& a, const Edge& b) { return a.weight > b.weight; } }; void dijkstra(vector<vector<Edge>>& graph, int start, vector<int>& dist) { int n = graph.size(); // 初始化距离数组,并将起点的距离设为0 dist.resize(n, numeric_limits<int>::max()); dist[start] = 0; // 优先队列用于选择权重最小的边 priority_queue<Edge, vector<Edge>, cmp> pq; pq.push({start, 0}); while (!pq.empty()) { Edge cur = pq.top(); pq.pop(); int curNode = cur.to; int curWeight = cur.weight; // 如果当前边的权重大于已经找到的最短路径,则忽略该边 if (curWeight > dist[curNode]) { continue; } // 遍历当前节点的所有邻接节点 for (const Edge& next : graph[curNode]) { int nextNode = next.to; int nextWeight = next.weight; // 如果通过当前节点到达邻接节点的路径更短,则更新最短路径 if (curWeight + nextWeight < dist[nextNode]) { dist[nextNode] = curWeight + nextWeight; pq.push({nextNode, dist[nextNode]}); } } } } int main() { int n, m; // n为节点数,m为边数 cin >> n >> m; // 构建邻接表表示的图 vector<vector<Edge>> graph(n); for (int i = 0; i < m; i++) { int u, v, w; // 边的起点、终点和权重 cin >> u >> v >> w; graph[u].push_back({v, w}); } int start, end; // 起点和终点 cin >> start >> end; vector<int> dist; dijkstra(graph, start, dist); if (dist[end] == numeric_limits<int>::max()) { cout << "不存在从起点到终点的路径" << endl; } else { cout << "起点到终点的最短路径长度为:" << dist[end] << endl; } return 0; } ### 回答3: 下面是一个使用堆优化斯特算法的最短路径代码: ```python import heapq def dijkstra(graph, start): # 初始化距离字典,将起点到每个顶点的距离设为无穷大 distances = {node: float('inf') for node in graph} # 将起点的距离设为0 distances[start] = 0 # 使用堆来存储当前最小距离的顶点 heap = [(0, start)] while heap: # 弹出堆中最小距离的顶点 current_distance, current_node = heapq.heappop(heap) # 如果当前顶点距离已经大于之前计算的最小距离,则跳过该顶点 if current_distance > distances[current_node]: continue # 遍历当前顶点的邻居节点 for neighbor, weight in graph[current_node].items(): distance = current_distance + weight # 如果通过当前顶点到达相邻顶点的距离小于之前计算的最小距离,则更新距离并加入堆 if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(heap, (distance, neighbor)) return distances ``` 这个代码使用了字典来表示图,每个顶点作为键,与其相邻顶点及对应的权重作为值。斯特算法的核心是通过不断更新距离字典中的值来获得最短路径。通过使用堆来存储当前最小距离的顶点,可以提高算法的效率。算法首先将起点的距离设为0,然后将起点加入堆中。在每次循环中,弹出堆中的最小距离顶点,并更新其相邻顶点的最小距离。如果通过当前顶点到达相邻顶点的距离小于之前计算的最小距离,则更新距离,并将相邻顶点加入堆中。最后,返回最终的距离字典,其中键为顶点,值为起点到该顶点的最小距离。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值