Cod sursa(job #2900312)

Utilizator Alexandra_s29Alexandra Stroiu Alexandra_s29 Data 10 mai 2022 18:53:00
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

const int N = 100000;

vector <int> a[N + 1];
int d[N + 1];

int main()
{
    ifstream in("bfs.in");
    ofstream out("bfs.out");
    int n , m , s;
    in >> n >> m >> s;
    for(int i = 0; i < m; i++)
    {
        int x , y;
        in >> x >> y;
        a[x].push_back(y);///graf orientat
    }
    in.close();
    for(int i = 1; i <= n; i++)
    {
        d[i] = -1;
    }
    queue <int> q;
    q.push(s);
    d[s] = 0;
    while(!q.empty())
    {
        int x = q.front();
        q.pop();
        for(auto y: a[x])
        {
            if(d[y] == -1)
            {
                q.push(y);
                d[y] = 1 + d[x];
            }
        }
    }
    for(int i = 1; i <= n ; i++)
    {
        out << d[i] << " ";
    }
    out.close();
    return 0;
}