GastonFontenla

Grafo {Estructura de Datos]

May 19th, 2017
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. struct Grafo
  7. {
  8.     vector <vector <int> > adj; ///Esta es nuestra lista de adyacencia
  9.  
  10.     void leer()
  11.     {
  12.         int n, m;
  13.         cin >> n >> m; ///Leo nodos y aristas
  14.  
  15.         adj.resize(n+1); ///Le doy tamaño a la lista
  16.  
  17.         int desde, hasta;
  18.         for(int i=0; i<m; i++)
  19.         {
  20.             cin >> desde >> hasta;
  21.             adj[desde].push_back(hasta);
  22.             adj[hasta].push_back(desde); ///Suponiendo que es bidireccional
  23.         }
  24.     }
  25.  
  26.     void mostrar()
  27.     {
  28.         cout << "Lista de adyacencia: " << endl;
  29.         for(int i=1; i<adj.size(); i++)
  30.         {
  31.             cout << "Adj[" << i << "]: ";
  32.             for(int j=0; j<adj[i].size(); j++)
  33.             {
  34.                 cout << adj[i][j] << " ";
  35.             }
  36.             cout << endl;
  37.         }
  38.     }
  39. };
  40.  
  41. int main()
  42. {
  43.     Grafo g;
  44.     g.leer();
  45.     g.mostrar();
  46.  
  47.     /**
  48.     Input de ejemplo:
  49.     5 4
  50.     1 2
  51.     1 3
  52.     1 4
  53.     1 4
  54.  
  55.     Output de ejemplo:
  56.     Lista de adyacencia:
  57.     Adj[1]: 2 3 4 4
  58.     Adj[2]: 1
  59.     Adj[3]: 1
  60.     Adj[4]: 1 1
  61.     Adj[5]:
  62.     **/
  63.  
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment