Cod sursa(job #2527905)

Utilizator nTropicGravityesadasdwaadwqafr nTropicGravity Data 21 ianuarie 2020 08:13:34
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include    <bits/stdc++.h>

using namespace std;

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

#define MAXN 100005

queue <int> q;
vector <int> edge[MAXN];

int m, n, x, y, current, start;
int dist[MAXN];

void bfs() {
    while(!q.empty()) {
        current = q.front();
        q.pop();

        for (size_t i = 0; i < edge[current].size(); i++) {
            int next = edge[current][i];

            if (dist[next] == -1) {
                dist[next] = dist[current] + 1;

                q.push(next);
            }
        }
    }
}

int main() {
    fin >> n >> m >> start;

    for (int i = 1; i <= m; i++) {
        fin >> x >> y;

        edge[x].push_back(y);
    }

    for (int i = 1; i <= n; i++)
        dist[i] = -1;

    dist[start] = 0;

    q.push(start);

    bfs();

    for (int i = 1; i <= n; i++)
        fout << dist[i] << " ";
}