当前位置:   article > 正文

求解最小跳数_局域网中求最小跳数

局域网中求最小跳数

  1. #include<iostream>
  2. #include<algorithm>
  3. #include<queue>
  4. #define MAX 1000000
  5. #define MAXInt 31245
  6. using namespace std;
  7. typedef pair<int,int> Pair;//用优先队列选取权重最小的节点
  8. priority_queue<Pair,vector<Pair>,greater<Pair> >que;
  9. typedef struct ArcNode{
  10. int adjvex;
  11. int weight;
  12. struct ArcNode* nextarc;
  13. }ArcNode;
  14. typedef struct VNode{
  15. bool vis;
  16. int wei;
  17. ArcNode *firstarc;
  18. }VNode;
  19. typedef struct{
  20. VNode* vertice;
  21. int vexnum,arcnum;
  22. }ALGraph;
  23. void Creat(ALGraph &G){
  24. G.vertice=new VNode[MAX];
  25. for(int k=0;k<MAX;k++){
  26. G.vertice[k].firstarc=NULL;
  27. G.vertice[k].vis=false;
  28. G.vertice[k].wei=MAXInt;
  29. }
  30. for(int i=0;i<G.arcnum;i++){
  31. int v1,v2;
  32. cin>>v1>>v2;
  33. ArcNode *pe=new ArcNode;
  34. pe->adjvex=v2;
  35. pe->nextarc=G.vertice[v1].firstarc;
  36. G.vertice[v1].firstarc=pe;
  37. ArcNode *ep=new ArcNode;
  38. ep->adjvex=v1;
  39. ep->nextarc=G.vertice[v2].firstarc;
  40. G.vertice[v2].firstarc=ep;
  41. }
  42. }
  43. void Dij(ALGraph &G,int s){
  44. G.vertice[s].wei=0;
  45. que.push(Pair(0,s));
  46. while(!que.empty()){
  47. Pair tmp=que.top();
  48. que.pop();
  49. int v=tmp.second;//节点
  50. int w=tmp.first;//权重
  51. if(G.vertice[v].vis==true)
  52. continue;
  53. else
  54. G.vertice[v].vis=true;
  55. ArcNode *p=G.vertice[v].firstarc;
  56. while(p!=NULL){
  57. int v0=p->adjvex;
  58. if(w+1<G.vertice[v0].wei&&!G.vertice[v0].vis){
  59. G.vertice[v0].wei=G.vertice[v].wei+1;
  60. que.push(Pair(G.vertice[v0].wei,v0));
  61. }
  62. p=p->nextarc;
  63. }
  64. }
  65. }
  66. int main(){
  67. /*
  68. 11 0 8
  69. 0 1 6
  70. 0 2 4
  71. 0 3 5
  72. 1 4 1
  73. 2 4 1
  74. 3 5 2
  75. 4 6 9
  76. 4 7 7
  77. 5 7 4
  78. 6 8 2
  79. 7 8 4
  80. */
  81. ALGraph G;
  82. int s,e;
  83. cin>>G.arcnum>>s>>e;//输入边数,起点,终点
  84. Creat(G);
  85. Dij(G,s);
  86. if(G.vertice[e].wei!=MAXInt)
  87. cout<<G.vertice[e].wei<<endl;
  88. else
  89. cout<<-1<<endl;
  90. delete []G.vertice;
  91. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/518726
推荐阅读
相关标签
  

闽ICP备14008679号