Cod sursa(job #3357535)

Utilizator TonyyAntonie Danoiu Tonyy Data 10 iunie 2026 20:55:31
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");

struct Node {
    int value;
    Node* next;

    Node(int value, Node* next = nullptr) : value(value), next(next) {}
};

struct Queue {
    Node* head = nullptr;
    Node* tail = nullptr;

    void push(int value) {
        Node* temp = new Node(value);
        if (!head) {
            head = tail = temp;
        }
        else {
            tail->next = temp;
            tail = temp;
        }
    }

    void pop() {
        Node* temp = head;
        head = head->next;
        delete temp;
    }

    int front() {
        return head->value;
    }

    bool empty() {
        return !head;
    }
};

const int nMax = 1e5 + 1;
int n, m, s;
vector<int> List[nMax], d(nMax, -1);
Queue q;

void bfs(int node) {
    q.push(node);
    d[node] = 0;
    while (!q.empty()) {
        node = q.front();
        q.pop();
        for (const int& i : List[node]) {
            if (d[i] == -1) {
                d[i] = d[node] + 1;
                q.push(i);
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(false);

    fin >> n >> m >> s;
    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;
        List[x].push_back(y);
    }
    bfs(s);
    for (int i = 1; i <= n; i++) {
        fout << d[i] << " ";
    }

    fin.close();
    fout.close();
    return 0;
}