AlenAntonelli

Isenbaev's Number

May 23rd, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.01 KB | None | 0 0
  1. ///https://trello.com/c/0Qqn6lbD/21-timus-1837-isenbaevs-number
  2. ///http://acm.timus.ru/problem.aspx?space=1&num=1837
  3. #include <iostream>
  4. #include <vector>
  5. #include <map>
  6. #include <queue>
  7. #define INF (1<<29)
  8. using namespace std;
  9.  
  10. struct graf {
  11.     vector< vector<long> > ady;
  12.     map<string,long> mapa;
  13.     vector<long> dist;
  14.     long n, m;
  15.    
  16.     long dar_id (string pal)
  17.     {
  18.         if (mapa[pal]==0)
  19.             mapa[pal]=mapa.size();
  20.            
  21.         return mapa[pal];
  22.     }
  23.    
  24.     void BFS (long inicial)
  25.     {
  26.         queue<long> cola;
  27.        
  28.         cola.push(inicial);
  29.         dist[inicial]=0;
  30.        
  31.         while( cola.size() )
  32.         {
  33.             long nodo = cola.front();
  34.             cola.pop();
  35.            
  36.             for(long i=0; i<ady[nodo].size(); i++)
  37.             {
  38.                 long vecino = ady[nodo][i];
  39.                 if ( dist[nodo]+1 < dist[vecino] )
  40.                 {
  41.                     dist[vecino] = dist[nodo]+1;
  42.                     cola.push(vecino);
  43.                 }
  44.             }
  45.         }
  46.        
  47.         for(auto i:mapa)
  48.         {
  49.             cout<<i.first<<" ";
  50.             if(dist[i.second]!=INF)
  51.                 cout<<dist[i.second]<<endl;
  52.             else cout<<"undefined"<<endl;
  53.         }
  54.     }
  55.    
  56.     void leer ()
  57.     {
  58.         cin>>m;
  59.        
  60.         ady.resize(301);
  61.        
  62.         string A, B, C;
  63.         for(long i=0; i<m; i++)
  64.         {
  65.             cin>>A>>B>>C;
  66.             long a = dar_id(A);
  67.             long b = dar_id(B);
  68.             long c = dar_id(C);
  69.            
  70.             ady[a].push_back(b);
  71.             ady[a].push_back(c);
  72.             ady[b].push_back(a);
  73.             ady[b].push_back(c);
  74.             ady[c].push_back(a);
  75.             ady[c].push_back(b);
  76.         }
  77.        
  78.         n = mapa.size();
  79.         ady.resize(n+1);
  80.         dist = vector<long> (n+1,INF);
  81.        
  82.         BFS( mapa["Isenbaev"] );
  83.     }
  84. };
  85.  
  86. int main ()
  87. {
  88.     graf g;
  89.     g.leer();
  90.    
  91.     return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment