Cod sursa(job #1145248)

Utilizator andreiagAndrei Galusca andreiag Data 17 martie 2014 23:55:47
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.84 kb
#include <fstream>
#include <queue>
#include <string.h>
#include <vector>

using namespace std;
const int Nmax = 100005;
const int INF = 0x3f3f3f3f;

vector<int> G[Nmax];
int dist[Nmax];
queue<int> Q;

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

    memset(dist, INF, sizeof(dist));
    int N, M, s, a, b;

    f >> N >> M >> s;
    for (int e = 0; e < M; e++) {
        f >> a >> b;
        G[a].push_back(b);
    }

    dist[s] = 0;
    Q.push(s);

    while(!Q.empty()) {
        a = Q.front(); Q.pop();
        for (auto x: G[a])
        {
            if (dist[x] == INF)
            {
                dist[x] = dist[a] + 1;
                Q.push(x);
            }
        }
    }

    for (int i = 1; i <= N; i++)
        if (dist[i] == INF) g << -1 << ' ';
        else g << dist[i] << ' ';

    g << '\n';

    return 0;
}