Cod sursa(job #1425763)

Utilizator RaileanuCristian Raileanu Raileanu Data 27 aprilie 2015 23:28:33
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include<fstream>
#include <list>
#include <string.h>
using namespace std;
ifstream f1("bfs.in");
ofstream f2("bfs.out");
#define MX 100010

list <int> graf[MX], *C, *Urm;
int n,m, s, dist[MX];

int main()
{
    int i, x,y;
    f1>>n>>m>>s;
    for (i=1; i<=m; i++)
    {
        f1>>x>>y;
        graf[x].push_back(y);
    }

    memset(dist, -1, sizeof(dist) );
    C= new list <int>;
    Urm= new list <int>;

    C->push_back(s);

    int pas= 0;

    while ( !C->empty() )
    {
        while (!C->empty())
        {
            int x= C->front();
            C->pop_front();
            dist[x]= pas;

            while ( !graf[x].empty() )
            {
                if ( dist[ graf[x].front() ] == -1 )
                    Urm->push_back(graf[x].front() );

                graf[x].pop_front();
            }
        }

        pas++;
        swap(C, Urm);
    }

    for (i=1; i<=n; i++)
        f2<<dist[i]<<" ";
    f2.close();
    return 0;
}