当前位置:   article > 正文

实验13 求图的最短路径 求解城市的最短距离问题(C++)_任意两个城市之间的最短距离c++

任意两个城市之间的最短距离c++

实验13 求图的最短路径 求解城市的最短距离问题

问题描述:

实现代码(spfa):    

  1. #include<iostream>
  2. #include<queue>
  3. #include<cstring>
  4. using namespace std;
  5. const int N = 100010;
  6. int e[N], ne[N], w[N], h[N], idx;
  7. int dist[N];
  8. bool st[N]; // 此法的st数组表示的是否在que中
  9. int n, m;
  10. void add(int a, int b, int c)
  11. {
  12. e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
  13. }
  14. int spfa()
  15. {
  16. memset(dist, 0x3f, sizeof dist);
  17. dist[1] = 0;
  18. queue<int> q;
  19. q.push(1);
  20. st[1] = true;
  21. while (q.size())
  22. {
  23. int t = q.front();
  24. q.pop();
  25. st[t] = false;
  26. for (int i = h[t]; i != -1; i = ne[i])
  27. {
  28. int j = e[i];
  29. if (dist[j] > dist[t] + w[i])
  30. {
  31. dist[j] = dist[t] + w[i];
  32. if (!st[j])
  33. {
  34. q.push(j);
  35. st[j] = true;
  36. }
  37. }
  38. }
  39. }
  40. return dist[n];
  41. }
  42. int main()
  43. {
  44. cin >> n >> m;
  45. memset(h, -1, sizeof h);
  46. while (m--)
  47. {
  48. int a, b, c;
  49. cin >> a >> b >> c;
  50. add(a, b, c); //邻接表不用考虑重边的问题
  51. }
  52. int t = spfa();
  53. if (t == 0x3f3f3f3f) puts("impossible");
  54. else
  55. {
  56. cout << t << endl;
  57. }
  58. return 0;
  59. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/243591
推荐阅读
相关标签
  

闽ICP备14008679号