Dijkstra(优先队列优化)
2015-08-10 14:19
501 查看
/* Dijkstra的算法思想: 在所有没有访问过的结点中选出dis(s,x)值最小的x 对从x出发的所有边(x,y),更新 dis(s,y)=min(dis(s,y),dis(s,x)+dis(x,y)) */ #include <iostream> #include <cstdio> #include <queue> #include <vector> using namespace std; const int Ni = 10000; const int INF = 1<<27; struct node{ int x,d; node(){} node(int a,int b){x=a;d=b;} bool operator < (const node & a) const { if(d==a.d) return x<a.x; else return d > a.d; } }; vector<node> eg[Ni]; int dis[Ni],n; void Dijkstra(int s) { int i; for(i=0;i<=n;i++) dis[i]=INF; dis[s]=0; //用优先队列优化 priority_queue<node> q; q.push(node(s,dis[s])); while(!q.empty()) { node x=q.top();q.pop(); for(i=0;i<eg[x.x].size();i++) { node y=eg[x.x][i]; if(dis[y.x]>x.d+y.d) { dis[y.x]=x.d+y.d; q.push(node(y.x,dis[y.x])); } } } } int main() { int a,b,d,m; while(scanf("%d%d",&n,&m),n+m) { for(int i=0;i<=n;i++) eg[i].clear(); while(m--) { scanf("%d%d%d",&a,&b,&d); eg[a].push_back(node(b,d)); eg[b].push_back(node(a,d)); } Dijkstra(1); printf("%d\n",dis ); } return 0; } /* 6 6 1 2 2 3 2 4 1 4 5 2 5 2 3 6 3 5 6 3 */
相关文章推荐
- ProGuard Version5.2(4.1)Manual-->Introduction
- ASP入门(三)-VBScript变量、运算符
- A Plug for UNIX
- 代码流程分析二:Settings-蓝牙分析-myDevice根preference分析
- 欢迎使用CSDN-markdown编辑器
- 题解分析及总结:经典逻辑面试题“假设有一个池塘,里面有无穷多的水,现有2个空水壶,如何使用少于15L的水,用2个水壶从池塘里取得3升水”
- 大数据学习之BigData常用算法和数据结构
- 安卓欢迎界面和activity之间的跳转问题
- Android/Kernel代码阅读工具之OpenGrok
- A Plug for UNIX 分类: POJ 图论 函数 2015-08-10 14:18 2人阅读 评论(0) 收藏
- 同时共用MOB公司的shareSDK和SMSSDK的冲突问题
- Linux/OS X下将Jar包转换成可直接执行文件(不用java -jar)
- 动画知识点汇总
- 设计模式--代理模式
- loadrunner的术语,分析等。破解
- 线段树之HDU3974 Assign the task
- UNITY3D学习笔记12
- opencv轮廓高级应用(轮廓匹配,几何直方图)
- a declaration here must declare aparameter
- Java的TreeMap统计单词数量