Cod sursa(job #1470271)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 10 august 2015 17:54:24
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <bits/stdc++.h>

#define DIM 2000005
#define Nmax 100005
#define Qmax 200005
using namespace std;

int cnt,st = 1,dr,N,M,S;;
array<int,DIM> Buff,Next;
array<int,Nmax> Cap,dist;
array<int,Qmax> Quad;

void add(int x,int y)
{
    Buff[++cnt] = y;
    Next[cnt] = Cap[x];
    Cap[x] = cnt;
}

void Read()
{
    scanf("%d%d%d\n",&N,&M,&S);
    int a,b;
    for(int i = 1; i <= M; ++i)
    {
        scanf("%d%d",&a,&b);
        add(a,b);
    }
}

void BFS(int k)
{
    Quad[++dr] = k;
    dist[k] = 1;
    while(st <= dr)
    {
        k = Quad[st++];
        for(int v = Cap[k]; v; v = Next[v])
            if( !dist[Buff[v]] )
            {
                dist[Buff[v]] = dist[k] + 1;
                Quad[++dr] = Buff[v];
            }
    }
    for(int i = 1; i <= N; ++i)
        printf("%d ",dist[i]-1);
}

int main()
{
    freopen("bfs.in","r",stdin);
    freopen("bfs.out","w",stdout);

    Read();
    BFS(S);

    return 0;
}