Cod sursa(job #3149542)

Utilizator AndreiKatsukiAndrei Dogarel AndreiKatsuki Data 9 septembrie 2023 18:27:30
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("bfs.in");
ofstream g("bfs.out");

const int NMAX = 1e5 + 5;

vector<int> G[NMAX];
int n, m, s, cost[NMAX];
bool checked[NMAX];

void bfs(int nod){
    checked[nod] = true;
    queue<int> q;
    q.push(nod);
    while(!q.empty()){
        int x = q.front();
        q.pop();
        for(auto i : G[x]){
            if(!checked[i]){
                q.push(i);
                cost[i] = cost[x] + 1;
                checked[i] = true;
            }
        }
    }
}

int main(){
    f >> n >> m >> s;
    for(int i = 1; i <= m; ++i){
        int x, y;
        f >> x >> y;
        G[x].push_back(y);
    }
    bfs(s);
    for(int i = 1; i <= n; ++i){
        if(!checked[i]){
            g << -1 << " ";
        }
        else{
            g << cost[i] << " ";
        }
    }
    return 0;
}