Cod sursa(job #3157765)

Utilizator georgeilie4542Ilie George georgeilie4542 Data 16 octombrie 2023 20:10:26
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>
using namespace std;

const int nrnoduri = 1000000;
vector<int> g[nrnoduri + 1];
int vizitati[nrnoduri + 1], distanta[nrnoduri + 1];

void BFS(int x) {
    queue<int> q;
    q.push(x);
    vizitati[x] = 1;
    distanta[x] = 0;
    while (!q.empty()) {
        x = q.front();
        q.pop();
        for (auto next : g[x]) {
            if (!vizitati[next]) {
                q.push(next);
                vizitati[next] = 1;
                distanta[next] = distanta[x] + 1;
            }
        }
    }
}

int main() {
    ifstream f("bfs.in");
    ofstream h("bfs.out");
    int N, M, S;
    f >> N >> M >> S;
    for (int i = 1; i <= M; i++) {
        int x, y;
        f >> x >> y;
        g[x].push_back(y);
    }
    BFS(S);
    for (int i = 1; i <= N; i++) {
        if (i != S && distanta[i] == 0) h << -1 << " ";
        else h << distanta[i] << " ";
    }
    return 0;
}