博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hdoj 2544 最短路径 dijkstra + 优先队列
阅读量:4216 次
发布时间:2019-05-26

本文共 1651 字,大约阅读时间需要 5 分钟。

这题 注意点 :

    用vector模拟 邻接表每个Case需要 清空vector (切记)

   可以只用一个Edge对象 同时表示 优先队列的(顶点,距离)对象 又表示边集合

  优先队列 比较的两种写法 一种写成friend形式(不能加const) 一种末尾必须加const

0ms AC

#include
#include
#include
#define MAXN 105#define INF 9999999#define MAXM 10005using namespace std;struct Edge{ int to, w; Edge(){} Edge(int t, int we){ to = t; w = we; } bool operator < (const Edge &o) const{ return w > o.w; } };//struct Node{//可以用 Edge取代 这个// int u, d;// Node(){}// Node(int u1, int d1):u(u1),d(d1){}//这是 初始化列表的方法// friend bool operator < (const Node &a, const Node &b){// return a.d > b.d;// } //};int n, m;bool vis[MAXN];int dis[MAXN];vector
adj[MAXN];int dijkstra(){ priority_queue
pq; memset(vis,false, sizeof(vis)); memset(dis,INF,sizeof(dis)); dis[1] = 0; pq.push(Edge(1,0)); while(!pq.empty()){ Edge t = pq.top(); int cur = t.to; if(cur == n){ return dis[n]; } vis[cur] = true;//每次只有这里(距离确定的时候设置为已经访问) pq.pop(); for(int i = 0; i < adj[cur].size(); ++i){ Edge e = adj[cur][i];//貌似 不能直接用 adj[i][j]当Edge用 if(!vis[e.to]){ if(dis[e.to] > dis[cur] + e.w){ dis[e.to] = dis[cur] + e.w; pq.push(Edge(e.to, dis[e.to]));// (顶点,距离) } } } }}int main() { int i, j, a, b, c; while(scanf("%d%d",&n,&m) && n!=0 && m!=0){ for(i = 1; i <= n; ++i) adj[i].clear(); //一定 记得清除 数据 for(i = 1; i <= m; ++i){ scanf("%d%d%d",&a,&b,&c); adj[a].push_back(Edge(b,c)); adj[b].push_back(Edge(a,c)); } int ans = dijkstra(); printf("%d\n",ans);// for(i = 1; i <= n; ++i){// for(j = 0; j < adj[i].size(); ++j){// Edge e = adj[i][j];// printf("%d %d %d\n",i,e.to,e.w);// } // } } }

转载地址:http://amimi.baihongyu.com/

你可能感兴趣的文章
【iOS游戏开发】icon那点事 之 图标设计(三)
查看>>
【IOS游戏开发】之测试发布(Distribution)
查看>>
【IOS游戏开发】之IPA破解原理
查看>>
【一天一道LeetCode】#45. Jump Game II
查看>>
【一天一道LeetCode】#56. Merge Intervals
查看>>
【一天一道LeetCode】#58. Length of Last Word
查看>>
【一天一道LeetCode】#59. Spiral Matrix II
查看>>
【一天一道LeetCode】#30. Substring with Concatenation of All Words
查看>>
【一天一道LeetCode】#60. Permutation Sequence.
查看>>
【一天一道LeetCode】#118. Pascal's Triangle
查看>>
JAVA实现文件树
查看>>
ebay api GetMyMessages 函数
查看>>
手动12 - 安装php加速器 Zend OPcache
查看>>
set theme -yii2
查看>>
yii2 - controller
查看>>
yii2 - 增加actions
查看>>
php图像处理函数大全(缩放、剪裁、缩放、翻转、旋转、透明、锐化的实例总结)
查看>>
magento url中 uenc 一坨编码 base64
查看>>
强大的jQuery焦点图无缝滚动走马灯特效插件cxScroll
查看>>
Yii2.0 数据库查询
查看>>