Cod sursa(job #2415834)

Utilizator andreisontea01Andrei Sontea andreisontea01 Data 26 aprilie 2019 15:40:34
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 100005;

vector<int> graf[MAXN];
queue<int> q;
int dist[MAXN];

int main()
{
    ifstream fin("bfs.in");
    ofstream fout("bfs.out");
    int n, m, s, x, y;
    fin >> n >> m >> s;
    while(m){
        fin >> x >> y;
        graf[x].push_back(y);
        m--;
    }
    for(int i = 1; i <= n; ++i)
        dist[i] = 1e9;
    q.push(s);
    dist[s] = 0;
    while(!q.empty()){
        int nod = q.front();
        q.pop();
        for(auto x : graf[nod]){
            if(dist[x] > dist[nod] + 1){
                dist[x] = dist[nod] + 1;
                q.push(x);
            }
        }
    }
    for(int i = 1; i <= n; ++i){
        if(dist[i] < 1e9) fout << dist[i] << " ";
        else fout << "-1 ";
    }
    return 0;
}