Advertisement
HmHimu

DIJESTRA

Jul 20th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1.  
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. int adj[100][100];
  6. int d[100];
  7. int v;
  8.  
  9. struct edge
  10. {
  11. int node;
  12. int distance;
  13.  
  14. bool operator < (const edge& p) const
  15. {
  16. return distance>p.distance;
  17. }
  18. };
  19.  
  20. void dijkstra(int source)
  21. {
  22. priority_queue<edge> p; //a priority queue is an abstract data type which is like a regular queue or stack data structure,
  23. //but where additionally each element has a "priority" associated with it. In a priority queue, an element with high priority is served before
  24. //an element with low priority. If two elements have the same priority, they are served according to their order in the queue
  25.  
  26. for(int i=1;i<=v;i++)
  27. {
  28. d[i]=1000000;
  29. }
  30.  
  31. d[source]=0;
  32.  
  33. edge temp;
  34.  
  35. temp.distance=0;
  36. temp.node=source;
  37.  
  38. p.push(temp);
  39.  
  40. while(!p.empty())
  41. {
  42. temp=p.top();
  43. p.pop();
  44.  
  45. for(int i=1;i<=v;i++)
  46. {
  47. if(adj[temp.node][i]!=0)
  48. {
  49. edge t;
  50.  
  51. t.node=i;
  52. t.distance=d[temp.node]+adj[temp.node][i];
  53.  
  54. if(d[i]>t.distance)
  55. {
  56. d[i]=t.distance;
  57. p.push(t);
  58. }
  59. }
  60. }
  61. }
  62. }
  63.  
  64. int main()
  65. {
  66. int a,b,w,count=1;
  67.  
  68. cout<<"Enter number of Vartex : ";
  69. cin>>v;
  70.  
  71. while(1)
  72. {
  73. cout<<"Edge "<<count<<" : ";
  74.  
  75. cin>>a>>b>>w;
  76.  
  77. if(a>v || b>v)
  78. {
  79. cout<<"Wrong input"<<endl;
  80. }
  81. else if(a==0 && b==0)
  82. {
  83. break;
  84. }
  85. else
  86. {
  87. adj[a][b]=w;
  88. count++;
  89. }
  90. }
  91.  
  92. dijkstra(1);
  93.  
  94. for(int i=1;i<=v;i++)
  95. {
  96. cout<<d[i]<<" ";
  97. }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement