Dijkstra+优先队列
2024-09-18 01:29:24
/*
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 = ;
const int INF = <<;
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=; i<=n; i++) dis[i]=INF;
dis[s]=;
//用优先队列优化
priority_queue<node> q;
q.push(node(s,dis[s]));
while(!q.empty())
{
node x=q.top();
q.pop();
for(i=; 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=; 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();
printf("%d\n",dis[n]);
}
return ;
}
/*
6 6
1 2 2
3 2 4
1 4 5
2 5 2
3 6 3
5 6 3
*/
最新文章
- Lesson 10 Not for jazz
- Noip2014 提高组 T2 联合权值 连通图+技巧
- MySQL指定mysqld启动时所加载的配置文件
- struts2 action获取ajax提交数据中文乱码问题
- MySQL 字段常用操作 添加,修改,删除,调整字段顺序
- mysql 错误- 磁盘空间不足,
- WEB黑客工具箱之LiveHttpHeaders介绍
- Python操作 Memcache、Redis、RabbitMQ、SQLAlchemy
- 随应潮流-基于ABP+Angulsrjs现代化应用软件开发框架(2)-abp说明
- web 前端路线
- CentOS 6.5 安装MySQL过程
- ASP.NET Core WebAPI控制器返回类型的最佳选项
- BZOJ5419[Noi2018]情报中心——线段树合并+虚树+树形DP
- 归并排序(Python实现)
- Axure8.0从入门到精通
- JAVA-JSP内置对象之response对象实现页面自动跳转
- Unity3D学习笔记(十八):动画内容补充
- 机器学习-ID3决策树算法(附matlab/octave代码)
- Python中的数据结构 --- 列表(list)
- cocos2d-x3.7 cclabel文字破碎,异常,变乱