Cod sursa(job #2683029)

Utilizator mihai002016Zaharia Teodor Mihai mihai002016 Data 10 decembrie 2020 11:29:52
Problema BFS - Parcurgere in latime Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <iostream>

using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int N, M, S,x,y,v[100002],cost[100002];
bool viz[100002];
struct nod {
    nod* urm;
    int val;
};
struct coada {
    int cost, nod;
}c[100002], n;
void BFS(int S, nod**l)
{
    int ic=0,sf=1;
    nod* x;
    c[1].nod = S;
    v[S] = 1;
    c[1].cost = 0;
    while (ic < sf)
    {
        n = c[++ic];
        x = l[n.nod];
        while (x != nullptr&& viz[x->val] == 0)
        {
            viz[x->val] = 1;
            c[++sf].nod = x->val;
            c[sf].cost = n.cost+1;
            cost[x->val] = n.cost + 1;
            x = x->urm;
        }
    }
}
int main()
{
    nod** l;
    fin >> N>>M>>S;
    l = new nod*[N];
    for (int i = 1; i <= N; i++)
        l[i] = nullptr;
    while (M)
    {
        nod* model = new nod();
        fin >> x >> y;
        model->urm = l[x];
        l[x] = model;
        l[x]->val = y;
        M--;
    }
    BFS(S,l);
    for (int i = 1; i <= N; i++)
    {
        if (i != S)
        {
            if (cost[i] != 0)
                fout << cost[i] << " ";
            else
                fout << -1 << " ";
        }
        else
            fout << 0 << " ";
    }
    return 0;
}