Cod sursa(job #1980674)

Utilizator robertstrecheStreche Robert robertstreche Data 13 mai 2017 19:50:39
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>
#include <bitset>
#include <vector>
#include <queue>

#define NMAX 200001
#define INF 2000000000

using namespace std;

bitset <NMAX> in_queue;
vector <int> v[NMAX];

int n;
int dist[NMAX];

inline void bfs(int source) {

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

    queue <int> q;
    q.push(source);
    dist[source] = 0;
    in_queue[source] = 1;

    while (q.empty() == 0) {

        int node = q.front();
        in_queue[node] = 0;
        q.pop();

        for (auto it : v[node])
            if (dist[node] + 1 < dist[it]) {
                dist[it] = dist[node] + 1;

                if (in_queue[it] == 0){

                    q.push(it);
                    in_queue[it] = 1;
                }
            }
    }

}

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

    int m, s, x, y;

    f >> n >> m >> s;

    for (int i = 0; i < m; i++) {
        f >> x >> y;

        v[x].push_back(y);
    }

    bfs(s);

    for (int i = 1; i <= n; i++)
        if (dist[i] != INF)
            g << dist[i] << " ";
        else
            g << -1 << " ";
    f.close();
    g.close();

    return 0;
}