hdu 1217 spfa最短路径

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





附件列表

    原文地址:https://www.cnblogs.com/sober-reflection/p/6964ed03bde265e267000a116207d879.html