Cod sursa(job #1397204)

Utilizator AnduuFMI Alexandru Banu Anduu Data 23 martie 2015 12:39:57
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <vector>
using namespace std;

vector<int> g[100005];
int c[100005], nrp[100005];
bool viz[100005];

int main () {
    int i, n, m, s, x, y, inc, sf;

    ifstream in ("bfs.in");
    in >> n >> m >> s;
    for (i = 1; i <= m; i++) {
        in >> x >> y;
        if (x != y)
            g[x].push_back(y);
    }
    in.close ();

    inc = sf = 1;
    c[inc] = s;
    viz[s] = 1;
    while (inc <= sf) {
        for (vector<int>::iterator it = g[c[inc]].begin(); it != g[c[inc]].end(); it++)
            if (!viz[*it]) {
                c[++sf] = *it;
                viz[c[sf]] = 1;
                nrp[c[sf]] = nrp[c[inc]] + 1;
            }
        inc++;
    }

    ofstream out ("bfs.out");
    for (i = 1; i <= n; i++)
        if (!nrp[i] && i != s)
            out << -1 << ' ';
        else out << nrp[i] << ' ';
    out << '\n';
    out.close ();

    return 0;
}