Advertisement
symonhasan

Uniform Cost Search

Dec 5th, 2019
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct node{
  4.     int cost , x;
  5.     node(){
  6.     }
  7.     node( int a , int b ){
  8.         x = a;
  9.         cost = b;
  10.     }
  11.     bool operator < ( const node& R )
  12.     const{
  13.         if( cost > R.cost )
  14.             return true;
  15.         if( cost == R.cost && R.x < x )
  16.             return true;
  17.         return false;
  18.     }
  19. };
  20. vector < node > G[ 1005 ];
  21. bool visited[ 10005 ];
  22. int cost[10005];
  23. void _ucs( node src )
  24. {
  25.     priority_queue < node > Q;
  26.  
  27.     Q.push( src );
  28.     visited[ src.x ] = 1;
  29.     cost[ src.x ] = 0;
  30.  
  31.     while( !Q.empty() )
  32.     {
  33.         node u = Q.top();
  34.         Q.pop();
  35.         cout << u.x << " ( " << u.cost << " ) ->  ";
  36.         for( auto it : G[ u.x ] )
  37.         {
  38.             if( !visited[ it.x ] )
  39.             {
  40.  
  41.                 visited[ it.x ] = 1;
  42.                 cost[ it.x ] = cost[ u.x ] + it.cost;
  43.                 Q.push( { it.x , cost[ it.x ] } );
  44.             }
  45.         }
  46. //        priority_queue < node > T = Q;
  47. //        cout << "QUEUE\n";
  48. //        while( !T.empty() )
  49. //        {
  50. //            cout << T.top().x << " " << T.top().cost << "\n";
  51. //            T.pop();
  52. //        }
  53. //        cout << "---\n";
  54.  
  55.     }
  56. }
  57.  
  58. int main(){
  59.     freopen("in.txt" , "r" , stdin );
  60.     int node , edge;
  61.     cin >> node >> edge;
  62.  
  63.     for( int i = 0; i < edge; i++ ){
  64.         int u , v , c;
  65.         cin >> u >> v >> c;
  66.         G[ u ].push_back( { v , c } );
  67.         G[ v ].push_back( { u , c } );
  68.     }
  69.     _ucs( { 1 , 0 } );
  70.     cout << endl;
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement