Cod sursa(job #2683244)

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

using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int N, M, S, x, y, cost[100005], ok;
bool viz[100005];
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;
    viz[S] = 1;
    c[1].cost = 0;
    while (ic < sf)
    {
        n = c[++ic];
        x = l[n.nod];
        while (x != nullptr) {
            if (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;
            }
            else
                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)
    {
        ok = 0;
        nod* model;
        fin >> x >> y;
        model = new nod;
        model->urm = l[x];
        l[x] = model;
        l[x]->val = y;
        M--;
    }
    BFS(S, l);
    delete 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;
}