Cod sursa(job #2881253)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 30 martie 2022 13:12:21
Problema BFS - Parcurgere in latime Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define dbg(x) cout << #x <<": " << x << "\n";
#define sz(x) ((int)x.size())

using ll = long long;

const string fn = "bfs";
ifstream fin(fn + ".in");
ofstream fout(fn + ".out");

const int mod = 1999999973;

int n,m;
vector<int> g[100005];
int d[100005];
bitset<100005> viz;
void bfs(int nod){
    queue<int> q;
    q.push(nod);
    while(!q.empty()){
        nod = q.front();
        q.pop();
        for(auto i : g[nod])
            if(d[i] > d[nod] + 1){
                d[i] = d[nod] + 1;
                cout << d[i] << " ";
                q.push(i);
            }
    }
}


int main(){
    int nod;
    fin >> n >> m >> nod;
    while(m--){
        int x, y;
        fin >> x >> y;
        g[x].pb(y);
    }
    for (int i = 1; i <= n; ++i)
        d[i] = 2e9;
    
    d[nod] = 0;
    bfs(nod);

    for (int i = 1; i <= n; ++i)
        if(d[i] != 2e9)
            fout << d[i] << " ";
        else
            fout << "-1 ";



    return 0;
}