Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. void relax(node& u, node& v, int cost){
  2.     if(v.cost > u.cost + cost){
  3.         v.cost = u.cost + cost;
  4.         v.parent = u.index;
  5.     }
  6. }
  7.  
  8. void djikstra(graph& g, int start){
  9.     priority_queue<pair<double, int>, vector<pair<double, int> >, greater<pair<double, int> > > pq;
  10.     for(int i = 0; i < g.nodes.size(); i++){
  11.         g.nodes[i].cost = INF;
  12.     }
  13.     g.nodes[start].cost = 0;
  14.     pq.push(mp(g.nodes[start].cost, start));
  15.     while(!pq.empty()){
  16.         int u = pq.top().second;
  17.         pq.pop();
  18.         if(g.nodes[u].visited == false){
  19.             g.nodes[u].visited = true;
  20.             for(int i = 0; i < g.edges[u].size(); i++){
  21.                 int adj = g.edges[u][i].first;         
  22.                 if(g.nodes[adj].visited == false){
  23.                     relax(g.nodes[u], g.nodes[adj], g.edges[u][i].second);
  24.                     pq.push(mp(g.nodes[adj].cost, adj));               
  25.                 }
  26.             }
  27.         }  
  28.     }
  29. }
  30.  
  31. void prim(graph& g, int start){
  32.     priority_queue<pair<double, int>, vector<pair<double, int> >, greater<pair<double, int> > > pq;
  33.     for(int i = 0; i < g.nodes.size(); i++){
  34.         g.nodes[i].cost = INF;
  35.     }
  36.     g.nodes[start].cost = 0;
  37.     pq.push(mp(g.nodes[start].cost, start));
  38.     while(!pq.empty()){
  39.         int u = pq.top().second;
  40.         pq.pop();
  41.         if(g.nodes[u].visited == false){
  42.             g.nodes[u].visited = true;
  43.             for(int i = 0; i < g.edges[u].size(); i++){
  44.                 int adj = g.edges[u][i].first; 
  45.                 if(g.nodes[adj].visited == false && g.edges[u][i].second < g.nodes[adj].cost){
  46.                     g.nodes[adj].cost = g.edges[u][i].second;
  47.                     g.nodes[adj].parent = u;
  48.                     pq.push(mp(g.nodes[adj].cost, adj));               
  49.                 }      
  50.             }
  51.         }  
  52.     }
  53.  
  54. }
  55.  
  56. void printMST(graph g){
  57.     for (int i = 0; i < g.nodes.size(); ++i){
  58.         if(g.nodes[i].parent != -1){
  59.             cout << min(g.nodes[i].index + 1, g.nodes[i].parent + 1) << " "
  60.                 <<  max(g.nodes[i].index + 1, g.nodes[i].parent + 1)  << endl;                 
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement