Cod sursa(job #2325764)

Utilizator sebistetuCucolas Sebastian sebistetu Data 22 ianuarie 2019 21:49:47
Problema BFS - Parcurgere in latime Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include<bits/stdc++.h>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");

const int Nmax = 100005;

queue<int>Q;
list<int> G[Nmax];
list<int>::iterator it;
int n, m, start, i, nod_curent, dist[Nmax], x ,y;

void citire() {

    f >> n >> m >> start;

    while(m--) {

        f >> x >> y;

        G[x].push_back(y);
    }
}

void BFS() {

    Q.push(start);

    for(i = 1; i <= n; ++i)
        dist[i] = -1;

    dist[start] = 0;

    while(!Q.empty()) {

        nod_curent = Q.front();

        for(it = G[nod_curent].begin(); it != G[nod_curent].end(); ++it)
            if(dist[*it] == -1){

                Q.push(*it);
                dist[*it] = dist[nod_curent] + 1;
            }
        Q.pop();
    }
}

int main() {

    citire();
    BFS();

    for(i = 1; i <= n; ++i)
        g << dist[i] << ' ';

        return 0;
}