Cod sursa(job #2721338)

Utilizator AlexZeuVasile Alexandru AlexZeu Data 11 martie 2021 18:41:04
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <bits/stdc++.h>
using namespace std;

int n, m, S;
vector<int> edges[1000100];
int dist[100100];
queue<int> q;

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

void bfs() {
    while(!q.empty()) {
        int node = q.front();
        q.pop();
        for (int i = 0; i < edges[node].size(); ++i) {
            if (dist[edges[node][i]] == INT_MAX) {
                dist[edges[node][i]] = dist[node] + 1;
                q.push(edges[node][i]);
            }
        }
    }
}

int main() {
    fin.tie(0);
    ios::sync_with_stdio(0);
    fin >> n >> m >> S;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        fin >> x >> y;
        edges[x].push_back(y);
    }
    for (int i = 1; i <= n; ++i) {
        dist[i] = INT_MAX;
    }
    q.push(S);
    dist[S] = 0;
    bfs();
    for (int i = 1; i <= n; ++i) {
        if (dist[i] == INT_MAX) {
            dist[i] = -1;
        }
        fout << dist[i] << " ";
    }
    return 0;
}