Cod sursa(job #2400359)

Utilizator AngelescuHoriaAngelescu Horia AngelescuHoria Data 8 aprilie 2019 17:42:38
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int NMAX = 100001;
const int MMAX = 1000001;
int q[NMAX], d[NMAX], lst[NMAX], urm[MMAX], nr, vf[MMAX], n, m, z, x, y, s, p;

void adauga(int x, int y)
{
    ++nr;
    vf[nr] = y;
    urm[nr] = lst[x];
    lst[x] = nr;
}

void bfs(int s)
{
    for(int i = 1; i <= n; i++)
    {
        d[i] = -1;
    }
    int st = 0, dr = -1;
    q[++dr] = s;
    d[s] = 0;
    while(st <= dr)
    {
        x = q[st++];
        for(p = lst[x]; p != 0; p = urm[p])
        {
            y = vf[p];
            if(d[y] == -1)
            {
                q[++dr] = y;
                d[y] = 1 + d[x];
            }
        }
    }
}

int main()
{
    fin >> n >> m >> z;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        adauga(x, y);
    }
    bfs(z);
    for(int i = 1; i <= n; i++)
    {
        fout << d[i] << " ";
    }
    fin.close();
    fout.close();
    return 0;
}