Cod sursa(job #2685213)

Utilizator teofilotopeniTeofil teofilotopeni Data 16 decembrie 2020 12:51:16
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <deque>
using namespace std;

struct Element{
    int val;
    Element* next = NULL;
};

void push(Element*& start, int val) {
    Element* nou = new Element;
    nou->next = start;
    start = nou;
    start->val = val;
}

int pop(Element*& start) {
    Element* vechi = start;
    start = start->next;
    return vechi->val;
}

struct Nod {
    int minim = -1;
    Element* from = NULL;
};

int main() {
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);
    int n, m, s, i, x, y;
    Nod nodes[100010];

    scanf("%d %d %d", &n, &m, &s);
    while (m--) {
        scanf("%d %d", &x, &y);
        push(nodes[x].from, y);
    }

    deque<int> parcurse(1, s);
    nodes[s].minim = 0;

    while (parcurse.size()) {
        while (nodes[parcurse[0]].from != NULL) {
            i = pop(nodes[parcurse[0]].from);
            if (nodes[i].minim < 0) {
                nodes[i].minim = nodes[parcurse[0]].minim + 1;
                parcurse.push_back(i);
            }
        }
        parcurse.pop_front();
    }
    for (i = 1; i <= n; i++)
        cout << nodes[i].minim << ' ';
    return 0;
}