dijkstra完整模板
来源:互联网 发布:kendalltau python 编辑:程序博客网 时间:2024/06/05 23:49
#include<cstdio>#include<cstring>#include<iostream>#include<iomanip>#include<queue>#include<cmath>#include<stack>#include<map>#include<vector>#include<set>#include<algorithm>using namespace std;typedef long long LL;const int int_max = 0x07777777;const int int_min = 0x80000000;const int maxn = 1000;struct HeapNode{ int u,d; bool operator < (const HeapNode& a) const { return d > a.d; }};struct Edge { int from, to, dist;};int n,m; //点数和边数vector<Edge> edges;vector<int> g[maxn];bool done[maxn];int d[maxn],p[maxn];void addedge (int from, int to, int dist){ edges.push_back((Edge){from, to, dist}); //若是无向图,则一个边要调用两次这个函数 m = edges.size(); g[from].push_back(m-1);}void dij (int s){ for(int i = 0; i < maxn; i++) d[i] = int_max; d[s] = 0; priority_queue<HeapNode> q; q.push((HeapNode){s,0}); while(!q.empty()){ HeapNode x = q.top(); q.pop(); int u = x.u; if(done[u]) continue; done[u] = true; for(int i = 0; i < g[u].size(); i++){ Edge& e = edges[g[u][i]]; if(d[e.to] > d[e.from] + e.dist){ d[e.to] = d[e.from] + e.dist; p[e.to] = g[u][i]; q.push((HeapNode){e.to,d[e.to]}); } } }}
用数组保存图,可以提高效率,参考如下。
#include<cstdio>#include<cstring>#include<iostream>#include<iomanip>#include<queue>#include<cmath>#include<stack>#include<map>#include<vector>#include<set>#include<algorithm>using namespace std;typedef long long LL;const int int_max = 0x07777777;const int int_min = 0x80000000;const int maxn = 31000;const int maxm = 160000;struct HeapNode{ int u,d; HeapNode(int _u, int _d):u(_u),d(_d){} bool operator < (const HeapNode& a) const { return d > a.d; }};struct Edge { int e,v;}es[160000];int neg;int node[maxn];int nexte[maxm];int n,m; bool done[maxn];int d[maxn],p[maxn];void addedge (int s, int e, int v){ es[neg].e = e; es[neg].v = v; nexte[neg] = node[s]; node[s] = neg++;}void dij (int s){ for(int i = 0; i <= n; i++) d[i] = int_max; memset(done, 0, sizeof(done)); d[s] = 0; priority_queue<HeapNode> q; q.push(HeapNode(s,0)); while(!q.empty()){ HeapNode x = q.top(); q.pop(); int u = x.u; if(done[u]) continue; done[u] = true; int p = node[u]; while (p!=-1) { if(d[es[p].e] > d[u]+es[p].v){ d[es[p].e] = d[u]+es[p].v; q.push(HeapNode(es[p].e,d[es[p].e])); } p = nexte[p]; } }}
0 0
- dijkstra完整模板
- dijkstra 模板
- dijkstra 模板
- Dijkstra模板
- dijkstra模板
- dijkstra模板
- Dijkstra模板
- (Dijkstra模板)
- Dijkstra模板
- Dijkstra模板
- Dijkstra 模板
- Dijkstra模板
- dijkstra 模板
- dijkstra模板
- dijkstra模板
- dijkstra模板
- [模板]Dijkstra
- dijkstra 模板
- Hibernate getCurrentSession 与 openSession() 的区别
- 【最短路径floyd算法】HDU 1869---六度分离
- 静态字典树和动态字典树模板
- 深入Linux设备驱动程序内核机制读书笔记
- IOS中延时执行的几种方式的比较和汇总
- dijkstra完整模板
- Android客户端和Servlet服务端的JSON传输(注释详细到啰嗦的地步,欢迎新手学习)
- 循环-06. 统计一行文本的单词个数
- POJ 1258 Agri-Net 最小生成树
- IOS开发之----远程推送通知
- HDOJ 2680 Choose the best route(最短路,dijkstra)
- 关于jQuery UI 使用心得及技巧
- block语法块的初级理解
- Linux下使用安腾认证连接校园网