dij(priority_queue)

#include <bits/stdc++.h>
using namespace std;
struct E{
	int from, to, cap;
};
struct HeapNode{
	int d, u;
	bool operator < (const HeapNode& rhs) const{
		return d > rhs.d;
	}
};
vector <E> edge;
vector <int> p[MAXN];
bool vis[MAXN];
int d[MAXN];
void read_graph (int from,int to,int cap)
{
 	edge.push_back((E){from, to, cap});
 	int m=edge.size();
 	p[from].push_back(m-1);
}
void dijkstra(int s)
{
	priority_queue <HeapNode> Q;
	for(int i=0; i<n; i++) d[i]=INF;
	d[s]=0;
	memset(vis, 0, sizeof(vis));
	Q.push((HeapNode){0,s});
	while( !Q.empty()){
		HeapNode x = Q.top(); Q.pop();
		int u = x.u;
		if(vis[u]) continue;
		vis[u] = 1;
		for(int i=0; i<p[u].size(); i++){
			E &e=edge[G[u][i]];
			if(d[e.to] > d[u]+e.cap){
				d[e.to] = d[u]+e.cap;
				p[e.to] = G[u][i];
				Q.push((HeapNode){d[e.to], e.to});
			}
		}
	}
}
int main(){
	return 0;
}



参考:刘汝佳紫书

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用堆优化的 Dijkstra 算法来求解最短路径的示例代码,其中使用了 vector 来表示图的邻接表: ```cpp #include <iostream> #include <vector> #include <queue> #include <limits> using namespace std; typedef pair<int, int> pii; const int INF = numeric_limits<int>::max(); vector<int> dijkstra(const vector<vector<pii>>& graph, int source) { int n = graph.size(); vector<int> dist(n, INF); dist[source] = 0; priority_queue<pii, vector<pii>, greater<pii>> pq; pq.push({0, source}); while (!pq.empty()) { int u = pq.top().second; int d = pq.top().first; pq.pop(); if (d > dist[u]) { continue; // 已经找到了更短的路径 } for (const auto& edge : graph[u]) { int v = edge.first; int w = edge.second; if (dist[u] + w < dist[v]) { dist[v] = dist[u] + w; pq.push({dist[v], v}); } } } return dist; } int main() { int n = 5; // 图的顶点数 int m = 7; // 图的边数 vector<vector<pii>> graph(n); // 构建图的邻接表 graph[0].push_back({1, 2}); graph[0].push_back({2, 4}); graph[1].push_back({2, 1}); graph[1].push_back({3, 7}); graph[2].push_back({3, 3}); graph[2].push_back({4, 5}); graph[3].push_back({4, 2}); graph[4].push_back({3, 1}); int source = 0; vector<int> dist = dijkstra(graph, source); cout << "Shortest distances from node " << source << ":" << endl; for (int i = 0; i < n; ++i) { cout << "Node " << i << ": " << dist[i] << endl; } return 0; } ``` 上述代码中,我们使用堆优化的 Dijkstra 算法来找到从源节点到其他节点的最短距离。图的邻接关系使用 vector<vector<pii>> 来表示,其中 pii 表示边的目标节点和权重。你可以根据需要修改图的顶点数、边数和邻接表来适应不同的场景。输出结果将会显示源节点到其他节点的最短距离。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值