Cod sursa(job #1180966)

Utilizator flore77Simion Florentin flore77 Data 1 mai 2014 15:47:21
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>
using namespace std;

int main() {
    ifstream in;
    in.open("bfs.in");
    ofstream out;
    out.open("bfs.out");
    int N, M, S, i, n1, n2, x;
    in >> N >> M >> S;
    vector<int> nodes[N];
    int dist[100100] = {0}, vizitat[100100] = {0};
    vector<int>::iterator it;
    queue<int> q;
    for (i = 0; i < M; i++) {
        in >> n1 >> n2;
        if (n1 != n2)
            nodes[n1].push_back(n2);
    }
    q.push(S);
    while (!q.empty()) {
        x = q.front();
        for (it = nodes[x].begin(); it != nodes[x].end(); it++) {
            if (vizitat[*it] == 0) {
                vizitat[*it] = 1;
                dist[*it] = dist[x] + 1;
                //cout << *it << " ";
                q.push(*it);
            }
        }
        vizitat[x] = -1;
        q.pop();
    }
    //cout << endl;
    for (i = 1; i <= N; i++) {
        if (i == S)
            out << "0" << " ";
        else if (dist[i] != 0)
            out << dist[i] << " ";
        else
            out << "-1" << " ";
    }
    in.close();
    out.close();
    return 0;
}