Cod sursa(job #804539)

Utilizator TodeaDariustodea darius TodeaDarius Data 29 octombrie 2012 22:11:36
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include<fstream>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
int n,m,s,viz[100005];
struct nod
{
    int inf;
    nod *adr;
} *v[100005];
void creare()
{
    f>>n>>m>>s;
    for(int i=1;i<=m;i++)
    {
        nod *p;
        int x,y;
        f>>x>>y;
        if(y!=s)
        {
            p=new nod;
            p->inf=y;
            p->adr=v[x];
            v[x]=p;
        }
    }
}
void bfs(int x)
{
    int c[100005];
    int pr,u;pr=u=1;
    c[pr]=x;viz[x]=1;int nr=1;
    while(pr<=u)
    {
        x=c[pr++];
        for(nod *p=v[x];p!=NULL;p=p->adr)
        {
            if(viz[p->inf]==0)
            {
                c[++u]=p->inf;
                viz[p->inf]=nr;
            }
        }
        nr++;
    }
}
int main()
{
    creare();
    bfs(s);
    for(int i=1;i<=n;i++)
    {
        if(i==s)
        {
            g<<0<<' ';
        }
        else
        {
            if(viz[i]==0 && i!=s)
            {
                g<<-1<<' ';
            }
            else{g<<viz[i]<<' ';}
        }
    }

}