最短路径快速spfa

  1. #include <stdio.h>
  2. #include <queue>
  3. #include <iostream>
  4. using namespace std;
  5. #define INF 0xfffff //因为为了辨别是否有负权,所以INF不能开太大
  6. #define MAX 1100
  7. int dist[MAX], pre[MAX], path[MAX][MAX];
  8. bool sign[MAX];
  9. void initialize(int n) //初始化
  10. {
  11. for(int i=1; i<=n; i++)
  12. {
  13. {
  14. //pre[i] = 0;
  15. dist[i] = INF; //将距离开始全变为最大
  16. sign[i] = false;
  17. }
  18. for(int j=1; j<=n; j++)
  19. path[i][j] = INF; //图初始
  20. }
  21. }
  22. void spfa(int n, int start) //无法计算负权
  23. {
  24. /* for (int i=1; i<=n; ++i) //初始化
  25. {
  26. dist[i] = INF;
  27. sign[i] = false;
  28. }*/
  29. queue<int> Q;
  30. dist[start] = 0;
  31. sign[start] = true;
  32. Q.push(start);
  33. while (!Q.empty()){
  34. int temp = Q.front();
  35. Q.pop();
  36. for (int i=0; i<=n; ++i)
  37. {
  38. if (dist[temp] + path[temp][i] < dist[i])//存在负权的话,就需要创建一个COUNT数组,当某点的入队次数超过V(顶点数)返回。
  39. {
  40. dist[i] = dist[temp] + path[temp][i];
  41. if (!sign[i])
  42. {
  43. Q.push(i);
  44. sign[i] = true;
  45. }
  46. //这个内循环可以判断所要权值相对应条件的值如dist[start];
  47. }
  48. }
  49. sign[temp] = false;
  50. }
  51. }
  52. void input(int line)
  53. {
  54. int a, b, weight;
  55. for(int i=0; i<line; i++)
  56. {
  57. scanf("%d%d%d", &a, &b, &weight);
  58. if(path[a][b] > weight) //有多条路,保存最短的那条
  59. {
  60. path[a][b] = weight;
  61. path[b][a] = weight; //无向图双向
  62. }
  63. }
  64. }
  65. int main()
  66. {
  67. int n, line;
  68. scanf("%d%d", &n, &line);
  69. initialize(n);
  70. input(line);
  71. spfa(n, 1);
  72. printf("%d\n\n", dist[n]);
  73. return 0;
  74. }





附件列表

     

    posted @ 2015-01-29 11:21  sober_reflection  阅读(180)  评论(0编辑  收藏  举报