// 再来一手精髓的Dijkstra
// 复杂度O( E*log(V) ) #include <cstdio>
#include <iostream>
#include <vector>
#include <queue> using namespace std; const int max_N = +;
const int max_E = +;
const int INF = 1e9; int N,E;
int d[max_N]; // 来自何方,已经不重要了。
// 实际上是在邻接表实现的过程中,行号即为来自的顶点
struct edge
{
int to,cost;
};
// P.first代表距离,P.second代表顶点编号
typedef pair<int,int> P; vector<edge> G[max_N]; // 这一个算法下来,我们在数组d中得到了从s点到其余所有顶点的最短路程
void dijkstra(int s)
{
// 建立最堆,来维护最小距离,可以降低一层复杂度
priority_queue< P,vector<P>,greater<P> > que; fill(d,d+N,INF);
d[s]=;
que.push(P(,s)); while(!que.empty())
{
// 取出一个顶点,看是否是Dijstra算法中,已经确定的最小顶点
P p=que.top();
que.pop(); int v=p.second;
// 让我们来看看这一步
// 首先,每次取出堆中的最小元素
// 然后去检索这个堆顶元素的标号所对应的距离
// 咦,你会发现堆顶这个距离,竟然比取出的最小元素还要小
// 惊讶?难道出错了?没有,考虑Dijkstra算法的流程,这个顶点肯定是之前已经确定过的最小顶点了,不需要考虑
// 之前的实现是多加了一个flag数组来标记,这里可以省去这部分内存,直接用这个条件来判断
if(d[v]<p.first)
{
continue;
} for(int i=;i<G[v].size();++i)
{
edge e=G[v][i];
if(d[e.to] > d[v] + e.cost)
{
d[e.to]=d[v]+e.cost;
// 数组中维护此次被更新的节点即可,其余节点不需要维护
que.push(P(d[e.to],e.to));
}
}
} } int main()
{
int a,b,c;
scanf("%d %d",&N,&E);
for(int i=;i<E;++i)
{
scanf("%d %d %d",&a,&b,&c);
edge e;
e.to=b;
e.cost=c;
G[a].push_back(e);
// 无向图
e.to=a;
e.cost=c;
G[b].push_back(e);
} dijkstra(); for(int i=;i<N;++i)
{
printf("%d ",d[i]);
} return ;
} /*
7 10
0 1 2
0 2 5
1 2 4
1 3 6
1 4 10
2 3 2
3 5 1
4 5 3
4 6 5
5 6 9 */

最新文章

  1. Android 7.1 - App Shortcuts
  2. Confuser.crproj
  3. [转载]config文件的一个很好的实现
  4. ubuntu安装python一些安装包
  5. 【bzoj2002】[Hnoi2010]Bounce 弹飞绵羊 link-cut-tree
  6. PHP模拟发送POST请求之三、用Telnet和fsockopen()模拟发送POST信息
  7. U-Mail邮件服务系统任意文件上传+执行漏洞(runtime缺陷与验证绕过)
  8. (干货)Linux学习资源推荐
  9. 元素属性和js数组
  10. rpc的学习
  11. hdu_5788_Level Up(树状数组+主席树)
  12. OC——继承
  13. PyInstaller Extractor安装和使用方法
  14. C++回顾day03---&lt;纯虚函数和抽象类以及虚析构函数,delete使用&gt;
  15. 从github上下载一个项目的子目录
  16. java中List按指定大小分割
  17. ps昏暗室内照片调成暖色光亮效果
  18. netty 在线教程
  19. c++中new的三种用法详细解析
  20. linux下automake用法

热门文章

  1. Liunx创建到部署ASP.NET Core项目从零开始-----使用Centos7
  2. [HAOI2015]树上操作(树链剖分)
  3. Docker获取镜像报错docker: Error response from daemon
  4. 浅谈openresty
  5. Shell环境变量文件
  6. Perl Tk在IC设计中的应用、Windows、Linux平台下的安装-各种错误的摸索解决
  7. 如何写出优雅的Python代码?
  8. 基于python2+selenium3+pytest4的UI自动化框架
  9. Jumpserver:跳板机
  10. 2.5D(伪3D)站点可视化第一弹