Cod sursa(job #3199232)

Utilizator VVasiuVasiu Vasile VVasiu Data 1 februarie 2024 08:44:09
Problema BFS - Parcurgere in latime Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <iostream>
#include <fstream>
using namespace std;
#define NN 100001
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int start[NN], t[2][2*NN];
int cost[NN] = {-1}, c[NN];
int n, m, plec, x, y, k;

void parc(int i, int &dr, int nod)
{
    if(t[1][i])
        parc(t[1][i], dr, nod);
    if(cost[t[0][i]] == -1)
    {
        c[++dr] = t[0][i];
        cost[t[0][i]] = cost[nod] + 1;
    }
}
void bfs(int plec)
{
    int st, dr;
    st = dr = 1;
    c[dr] = plec;
    cost[plec] = 0;
    while(st <= dr)
    {
        parc( start[c[st]], dr, c[st]);
        st++;
    }
}

int main()
{
    fin >> n >> m >> plec;
    while(fin >> x >> y)
    {
        k++;
        t[0][k] = y;
        t[1][k] = start[x];
        start[x] = k;
    }
    for(int i=1; i<=NN; i++)
        cost[i] = -1;
    bfs(plec);

    for(int i=1; i<=n; i++)
        fout << cost[i] << " ";
    return 0;
}