GastonFontenla

Untitled

Jun 12th, 2017
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #define INF (1 << 29) ///Significa 1x(2^29)
  5.  
  6. using namespace std;
  7.  
  8. struct Grafo
  9. {
  10.     vector <vector <int> > adj;
  11.     vector <int> dist; ///Vector de distancias
  12.     int nodos, aristas;
  13.     void leer()
  14.     {
  15.         cin >> nodos >> aristas;
  16.         adj.resize(nodos+1);
  17.         dist = vector <int> (nodos+1, INF);
  18.         int desde, hacia;
  19.         for(int i=0; i<aristas; i++)
  20.         {
  21.             cin >> desde >> hacia;
  22.             adj[desde].push_back(hacia);
  23.             adj[hacia].push_back(desde);
  24.         }
  25.     }
  26.  
  27.     void BFS(int n)
  28.     {
  29.         dist[n] = 0;
  30.         queue <int> cola;
  31.         cola.push(n);
  32.  
  33.         while(cola.size())
  34.         {
  35.             n = cola.front();
  36.             cola.pop();
  37.  
  38.             for(int i=0; i<adj[n].size(); i++)
  39.             {
  40.                 int vecino = adj[n][i];
  41.  
  42.                 if(dist[n]+1 < dist[vecino])
  43.                 {
  44.                     dist[vecino] = dist[n]+1;
  45.                     cola.push(vecino);
  46.                 }
  47.             }
  48.         }
  49.     }
  50.  
  51.     int resolver()
  52.     {
  53.         BFS(1);
  54.         int cant = 0;
  55.         for(int i=1; i<dist.size(); i++)
  56.             if(dist[i] < INF)
  57.                 cant++;
  58.  
  59.         return cant;
  60.     }
  61. };
  62.  
  63. int main()
  64. {
  65.     /**
  66.     Problema:
  67.     Dado un grafo, decir cuales son los nodos que son alcanzables desde el nodo 1.
  68.     **/
  69.  
  70.     Grafo g;
  71.     g.leer();
  72.  
  73.     cout << g.resolver() << endl;
  74.  
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment