Cod sursa(job #1976946)

Utilizator blatulInstitutul de Arta Gastronomica blatul Data 4 mai 2017 17:03:41
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>
using namespace std;

#define NMAX 100002
#define INF 1e9

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

vector<int> graf[NMAX];
int dist[NMAX];

void BFS(const int N, const int start) {

    for (int i = 1; i <= N; ++i)
        dist[i] = INF;

    queue<int> Q;

    dist[start] = 0;
    Q.push(start);

    while (!Q.empty()) {

        int nod = Q.front();
        Q.pop();

        for (auto& adj: graf[nod]) {

            if (dist[adj] > dist[nod] + 1) {
                dist[adj] = dist[nod] + 1;
                Q.push(adj);
            }
        }
    }
}

int main() {

    int N, M, start;

    fin >> N >> M >> start;

    int x, y;
    while (M--) {

        fin >> x >> y;

        graf[x].push_back(y);
    }

    BFS(N, start);

    for (int i = 1; i <= N; ++i)
        fout << (dist[i] != INF ? dist[i] : -1) << " ";

    return 0;
}