Cod sursa(job #2784317)

Utilizator RaresRacsanRares Racsan RaresRacsan Data 16 octombrie 2021 12:05:08
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

int sol[100001], n;
vector <int> a[100002];
queue <int> q;
int m, x, y, s, i;

void bfs(int s)
{
    int i, x;

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

    q.push(s);
    sol[s] = 0;

    while(!q.empty())
    {
        x = q.front();
        q.pop();

        for(i = 0; i < a[x].size(); i++)
        {
            if(sol[a[x][i]] == -1)
            {
                sol[a[x][i]] = sol[x] + 1;
                q.push(a[x][i]);
            }
        }
    }
}

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

    for(i = 1; i <= m; i++)
    {
        fin >> x >> y;
        a[x].push_back(y);
    }

    bfs(s);

    for(i = 1; i <= n; i++)
        fout << sol[i] << ' ';
    return 0;
}