Cod sursa(job #2445204)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 3 august 2019 10:23:23
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");

const int NMAX = 1e5;

int N, M, S;
vector <int> g[NMAX + 5];
bool d[NMAX + 5];

queue <int> q;
int dist[NMAX + 5];

void bfs(int source)
{
    d[source] = 1;
    q.push(source);

    while(!q.empty()) {

        int node = q.front();
        q.pop();

        for(auto it : g[node])
            if(!d[it])
                {
                    dist[it] = dist[node] + 1;
                    d[it] = 1;
                    q.push(it);
                }
    }
}

int main()
{
    fin >> N >> M >> S;

    for(int i = 1; i <= M; i++) {

        int a, b; fin >> a >> b;
        g[a].push_back(b);

    }

    bfs(S);

    for(int i = 1; i <= N; i++)
        if(dist[i] == 0 && i != S) fout << -1 << ' ';
        else fout << dist[i] << ' ';

    return 0;
}