GastonFontenla

Untitled

May 29th, 2017
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. #define INF (1 << 29) ///2^29 * 1 left shift
  5.  
  6. using namespace std;
  7.  
  8. struct Arista ///unidireccional
  9. {
  10.     int nodo;
  11.     int costo;
  12. };
  13.  
  14. Arista armar(int hasta, int costo)
  15. {
  16.     Arista ar;
  17.     ar.nodo = hasta;
  18.     ar.costo = costo;
  19.     return ar;
  20. }
  21.  
  22. struct Grafo
  23. {
  24.     vector <vector <Arista> > adj;
  25.     int nodos, aristas, inicio;
  26.  
  27.     void leer()
  28.     {
  29.         cin >> nodos >> aristas;
  30.  
  31.         adj.resize(nodos+1);
  32.  
  33.         int desde, hasta, costo;
  34.  
  35.         for(int i=0; i<aristas; i++)
  36.         {
  37.             cin >> desde >> hasta >> costo;
  38.             adj[desde].push_back(armar(hasta, costo));
  39.             adj[hasta].push_back(armar(desde, costo));
  40.         }
  41.  
  42.         cin >> inicio;
  43.     }
  44.  
  45.     int elegirMenor(const vector <int> &dist, const vector <bool> &usado)
  46.     {
  47.         int minDist = INF;
  48.         int nodoMin;
  49.         for(int i=0; i<dist.size(); i++)
  50.         {
  51.             if(dist[i] < minDist && usado[i] == false)
  52.             {
  53.                 minDist = dist[i];
  54.                 nodoMin = i;
  55.             }
  56.         }
  57.  
  58.         return nodoMin;
  59.     }
  60.  
  61.     void Dijkstra()
  62.     {
  63.         vector <int> dist(nodos+1, INF);
  64.         vector <bool> usado(nodos+1, false);
  65.  
  66.         dist[inicio] = 0;
  67.  
  68.         for(int i=0; i<nodos; i++)
  69.         {
  70.             int n = elegirMenor(dist, usado);
  71.             usado[n] = true;
  72.  
  73.             for(int j=0; j<adj[n].size(); j++)
  74.             {
  75.                 int vecino = adj[n][j].nodo;
  76.                 int costo = adj[n][j].costo;
  77.                 if(dist[n] + costo < dist[vecino])
  78.                 {
  79.                     dist[vecino] = dist[n] + costo;
  80.                 }
  81.             }
  82.         }
  83.  
  84.         cout << "Distancias desde el inicio hasta cada nodo: " << endl;
  85.  
  86.         for(int i=1; i<dist.size(); i++)
  87.         {
  88.             cout << dist[i] << ", ";
  89.         }
  90.         cout << endl;
  91.  
  92.     }
  93.  
  94. };
  95.  
  96. int main()
  97. {
  98.     Grafo g;
  99.     g.leer();
  100.     g.Dijkstra();
  101.  
  102.     return 0;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment