Cod sursa(job #2685177)

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

class Coada {
    struct Element{
        int val;
        Element* next = NULL;
    };
    Element* start = NULL;
public:
    int size = 0;

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

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

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

int main() {
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);
    int n, m, s, i, x, y;
    scanf("%d %d %d", &n, &m, &s);
    Nod nodes[100001];
    while (m--) {
        scanf("%d %d", &x, &y);
        nodes[x].from.push(y);
    }

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

    while (parcurse.size()) {
        while (nodes[parcurse[0]].from.size) {
            i = nodes[parcurse[0]].from.pop();
            if (!nodes[i].gasit) {
                nodes[i].minim = nodes[parcurse[0]].minim + 1;
                nodes[i].gasit = true;
                parcurse.push_back(i);
            }
        }
        parcurse.pop_front();
    }

    for (i = 1; i <= n; i++)
        cout << nodes[i].minim << ' ';
    return 0;
}