鱼C论坛

 找回密码
 立即注册
查看: 1878|回复: 0

求最短路的边数

[复制链接]
发表于 2022-7-26 15:47:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
给出一个无向图, 求 点1 -> 点n 的最短路, 并求出最短路上有几条边
最短路算法我可以了, 但是如何统计最短路上边数错了, 求一个方法, 我代码在下面:
  1. #include <bits/stdc++.h>
  2. using namespace std;

  3. struct edge{ // 边
  4.         int to, w;
  5. };
  6. struct node{ // 点
  7.         int code, dist;
  8. };
  9. struct cmp{
  10.         inline bool operator()(const node & a, const node & b){
  11.                 return a.dist > b.dist;
  12.         }
  13. };
  14. const int N = 20005;
  15. priority_queue<node, vector<node>, cmp> heap; // 堆优化
  16. vector<edge> e[N]; // 邻接矩阵
  17. bitset<N> vis; // 等同于 bool 数组
  18. int dist[N]; // 距离
  19. int path[N]; // 边的数量
  20. int n, m, a, b, c; // n个点, m条边, 由 a 到 b 的权值为 c 的边

  21. void dijkstra(){
  22.         vis.reset();
  23.         memset(dist, 0x3f, sizeof(dist));
  24.         memset(path, 0, sizeof(path)); // 初始化
  25.         dist[1] = 0;
  26.         heap.push({1, 0});
  27.         while(!heap.empty()){
  28.                 auto p = heap.top();
  29.                 heap.pop();
  30.                 if(vis[p.code]) continue;
  31.                 vis[p.code] = 1;
  32.                 for(auto ed : e[p.code]){
  33.                         if(dist[ed.to] > dist[p.code] + ed.w){
  34.                                 dist[ed.to] = dist[p.code] + ed.w;
  35.                                 heap.push({ed.to, dist[ed.to]});
  36.                                 path[ed.to] = path[p.code] + 1; // 这里加最短路的边 , 不知道为什么不对
  37.                         }
  38.                 }
  39.         }
  40. }

  41. int main(){
  42.         ios::sync_with_stdio(0);
  43.         cin.tie(0); cout.tie(0);
  44.        
  45.         cin >> n >> m;
  46.         for(int i = 0; i < m; i++){
  47.                 cin >> a >> b >> c;
  48.                 e[a].push_back({b, c});
  49.                 e[b].push_back({a, c});
  50.         }

  51.         dijkstra();

  52.         cout << dist[n] << ' ' << path[n] << endl;
  53.         for(int i = 1; i <= n; i++){
  54.                 cout << path[i] << ' '; // 就是这个边数求不对 , 求解
  55.         }
  56.        
  57.         return 0;
  58. }
复制代码

屏幕截图 2022-07-26 154657.png
输入 :
  1. 3 3
  2. 1 3 2
  3. 1 2 1
  4. 2 3 1
复制代码

输出 :
  1. 2 3
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-17 09:00

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表