Cod sursa(job #3036448)

Utilizator AndreiDeltaBalanici Andrei Daniel AndreiDelta Data 24 martie 2023 12:51:57
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <bits/stdc++.h>
#define pb push_back
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
typedef long long ll;
typedef pair<int, int> pi;
int t, T;

void BFS(int n, int start, vector<vector<int>>& V) {
    vector<int> d(n + 1, INT_MAX);
    vector<int> visited(n + 1, 0);
    queue<int> qu;
    qu.push(start);
    visited[start] = 1;
    d[start] = 0;
    while (!qu.empty()) {
        int nod = qu.front();
        qu.pop();
        visited[nod] = 2;

        for (int neigh : V[nod]) {
            if (!visited[neigh]) {
                visited[neigh] = 1;
                qu.push(neigh);
                d[neigh] = d[nod] + 1;
            }
        }
    }

    for (int i = 1; i <= n; i++)
        if (d[i] != INT_MAX)
            g << d[i] << ' ';
        else g << -1 << ' ';
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n, m, s;
    f >> n >> m >> s;
    vector < vector < int > > V(n + 1);
    for (int i = 1; i <= m; i++) {
        int a, b;
        f >> a >> b;
        V[a].pb(b);
    }

    BFS(n, s, V);

    return 0;
}