Cod sursa(job #2881254)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 30 martie 2022 13:13:04
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 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;


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;

  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);
            }
    }


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



    return 0;
}