Cod sursa(job #1323512)

Utilizator rockerboyHutter Vince rockerboy Data 21 ianuarie 2015 09:47:57
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <vector>
#include <list>
#include <queue>

std::ifstream in ("bfs.in");
std::ofstream out ("bfs.out");

int n, m, first;
std::vector< std::list<int> > x;
std::vector<int> dist;
std::vector<bool> seen;

void bfs (int first)
{
    std::queue<int> q;
    q.push (first);
    int current;
    std::list<int>::iterator i;

    while (not q.empty()) {
        current = q.front(); q.pop();

        for (i = x[current].begin(); i != x[current].end(); i++)
            if (!seen[*i]) {
                seen[*i] = true;
                dist[*i] = dist[current] + 1;
                q.push (*i);
            }
    }
}

int main()
{
    in >> n >> m >> first;
    x.resize (n+1);
    dist.resize (n+1, 0);
    seen.resize (n+1, false);

    int a, b, i;
    for (i=0; i<m; i++) {
        in >> a >> b;


        if (a == b && a == first) {
            seen[first] = true;
        }

        x[a].push_back (b);
    }

    bfs (first);
    dist[first] = -1;

    for (i=1; i<=n; i++) {
        if (dist[i] == 0) out << "-1 ";
        else if (dist[i] == -1) out << "0 ";
        else out << dist[i] << " ";
    }
}