Cod sursa(job #2035447)

Utilizator Alex18maiAlex Enache Alex18mai Data 9 octombrie 2017 12:51:40
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream cin ("bfs.in");
ofstream cout ("bfs.out");

vector <vector<int>> graf (100100);
vector <bool> used (100100);
vector <int> ans (100100);
queue <int> Q;

void bfs(){
    while(!Q.empty()){
        int now = Q.front();
        Q.pop();
        for (auto &x : graf[now]){
            if (!used[x]){
                Q.push(x);
                used[x] = true;
                ans[x] = ans[now] + 1;
            }
        }
    }
}

int main() {

    int node , vert , s;
    cin>>node>>vert>>s;

    for (int i=1; i<=vert; i++){
        int a , b;
        cin>>a>>b;
        if (a == b){
            continue;
        }
        graf[a].push_back(b);
    }
    Q.push(s);
    ans[s] = 0;
    used[s] = true;
    bfs();

    for (int i=1; i<=node; i++){
        if (ans[i] == 0 && i != s){
            cout<<-1<<" ";
        }
        else{
            cout<<ans[i]<<" ";
        }
    }

    return 0;
}