Cod sursa(job #363167)

Utilizator popoiu.georgeGeorge Popoiu popoiu.george Data 11 noiembrie 2009 23:10:44
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include<fstream>
#include<iostream>
#define inf "bfs.in"
#define outf "bfs.out"
#define MaxN 100002
#define MaxM 1000001
using namespace std;

fstream f(inf,ios::in),g(outf,ios::out);

int N,M,S;
int LA[2][MaxM],Start[MaxN];
int Cost[MaxN];
int Coada[MaxN],i_c=1,s_c=1;
int s[MaxN];

void Citire()
{
int i,j,k=0;
f>>N>>M>>S;
while(f>>i>>j)
    {
    k++;
    LA[1][k]=j;
    LA[0][k]=Start[i];
    Start[i]=k;
    }
for(i=1;i<=N;i++)Cost[i]=-1;
}

void BFS(int nod)
{
int aux;
Coada[i_c]=nod;
Cost[nod]=0;
s[nod]=1;
while(i_c<=s_c)
    {
    aux=Start[Coada[i_c]];
    while(aux)
        {
        if(s[LA[1][aux]]==0)
            {
            s[LA[1][aux]]=1;
            s_c++;
            Coada[s_c]=LA[1][aux];
            Cost[Coada[s_c]]=Cost[Coada[i_c]]+1;
            }
        aux=LA[0][aux];
        }
    i_c++;
    }
}

int main()
{
Citire();
BFS(S);
for(int i=1;i<=N;i++)g<<Cost[i]<<" ";
f.close();
g.close();
return 0;
}