Cod sursa(job #839124)

Utilizator bratualexBratu Alexandru bratualex Data 21 decembrie 2012 12:59:26
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <fstream>

using namespace std;
ifstream fin ("bfs.in");
ofstream fout("bfs.out");

struct nod {
    nod *next;
    int inf;
};



int main()
{
    nod *graf[100500],*pcoada,*ucoada;
    nod *x,*y;
    int i,m,n,s,a,b,k;
    int rez[100600],viz[100300];
    fin>>n>>m>>s;
    for(i=1;i<=n;i++)
    {
        rez[i]=0;
        viz[i]=0;
        graf[i]=new nod();
        graf[i]->next=NULL;

    }
    for ( i=1;i<=m;i++)
    {
        fin>>a>>b;
        x=new nod();
        x->inf=b;
        x->next=graf[a];
        graf[a]=x;
    }


    x=new nod();
    x=graf[s];
    viz[s]=1;
    pcoada=ucoada=x;
    viz[x->inf]=1;
    rez[x->inf]++;
    x=x->next;
    while (x->next)
    {
        //se poate sa fie mai multe muchii intre a,b. trebe verificat
        if (viz[x->inf]==0)
        {
            viz[x->inf]=1;
            rez[x->inf]++;
            y=new nod();
            ucoada->next=y;
            y->inf=x->inf;
            ucoada=y;
            x=x->next;
        }
        else
            x=x->next;
    }
    while ( pcoada )
    {
        k=pcoada->inf;
        //rez[k]++;


        x=new nod();
        x=graf[k];
        while (x)
        {
            if(viz[x->inf]==0)
            {
                viz[x->inf]=1;
                y=new nod();
                ucoada->next=y;
                y->inf=x->inf;
                ucoada=y;
                rez[y->inf]=rez[k]+1;
                x=x->next;
            }
            else
            {
                x=x->next;
            }
        }
        pcoada=pcoada->next;

     }
    for(i=1;i<=n;i++)
        if(viz[i])
        {
            fout<<rez[i]<<" ";
        }
        else
            fout<<"-1 ";
    fin.close();
    fout.close();
    return 0;
}