Cod sursa(job #2685211)

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

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

struct Coada {
    Element* start = NULL;

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

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

struct Nod {
    int minim = -1;
    Coada from;
};

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

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

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

    while (parcurse.size()) {
        while (nodes[parcurse[0]].from.start != NULL) {
            i = nodes[parcurse[0]].from.pop();
            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;
}