Cod sursa(job #3127711)

Utilizator sebuxSebastian sebux Data 7 mai 2023 18:57:06
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <bits/stdc++.h>
#define optim ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr)
#define ll long long
#define ull unsigned long long
#define pb push_back
#define popcount(x) __builtin_popcount(x)
#define ctzll(x) __builtin_ctzll(x)
#define clzll(x) __builtin_clzll(x)
using namespace std;

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


constexpr int sze = 100e3;
vector<int> G[sze + 1];
bitset<sze + 1> f;
int D[sze + 1];
void bfs(int x){
    queue<int> q;
    q.push(x);
    f[x] = 1;
    while (!q.empty())
    {
        int t = q.front();
        q.pop();

        for(int i : G[t]){
            if(!f[i]){
                f[i] = 1;
                q.push(i);
                D[i] = D[t] + 1;
            }
        }
        
    }
}


int main()
{
    int n, m, k;
    fin>>n>>m>>k;
    int x, y;
    while(m--){
        fin>>x>>y;
        G[x].pb(y);
    }
    bfs(k);
    for(int i = 1;i<=n;++i) {
        if(i == k) fout<<0<<' ';
        else if(D[i] == 0) fout<<"-1 ";
        else fout<<D[i]<<' ';
    }




    return 0;
}