Cod sursa(job #974769)

Utilizator 2dorTudor Ciurca 2dor Data 18 iulie 2013 12:09:33
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int MAXN = 100003;
queue<int> coada;
int n, m, s, a, b, pkt, nr, i;

struct nod {
    int cost;
    vector<int> neighbours;
}nods[MAXN];

void read() {
    fin >> n >> m >> s;
    for (int i = 1; i <= m; ++i) {
        fin >> a >> b;
        nods[a].neighbours.push_back(b);
    }
}

void go() {
    coada.push(s);
    nods[s].cost = 0;
    do {
        pkt = coada.front();//nodul actual
        coada.pop();
        nr = nods[pkt].neighbours.size();//nr vecini
        for (int i = 0; i < nr; ++i) {//parcurg toti vecinii
            if (nods[pkt].cost + 1 < nods[nods[pkt].neighbours[i]].cost) {
                nods[nods[pkt].neighbours[i]].cost = nods[pkt].cost + 1;
                coada.push(nods[pkt].neighbours[i]);
            }
        }
    }while (!coada.empty());
}

int main() {
    read();
    for (i = 1; i <= n; ++i)
        nods[i].cost = MAXN + 10;
    go();
    for (i = 1; i <= n; ++i) {
        if (nods[i].cost == MAXN + 10)
            fout << -1 << ' ';
        else
            fout << nods[i].cost << ' ';
    }
    fout << '\n';
    fin.close();
    fout.close();
    return 0;
}