Cod sursa(job #1740482)

Utilizator pfaaiFlorinel Salamiut pfaai Data 11 august 2016 17:16:56
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <vector>
#include <queue>

#define maxn 100005

using namespace std;

int n, m, s;
vector<int> a[maxn];
queue<int> q;
bool seen[maxn];
int d[maxn];

void bfs(int s) {
    q.push(s);
    seen[s] = true;
    d[s] = 0;

    while (!q.empty()) {
        int currentNode = q.front();
        q.pop();

        for (int i = 0; i < a[currentNode].size(); i++) {
            if (!seen[a[currentNode][i]]) {
                d[a[currentNode][i]] = d[currentNode] + 1;
                q.push(a[currentNode][i]);
                seen[a[currentNode][i]] = true;
            }
        }
    }
}

int main() {

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

    int x, y;
    in >> n >> m >> s;

    for (int i = 0; i < m; i++) {
        in >> x >> y;
        a[x].push_back(y);
    }

    bfs(s);

    for (int i = 1; i <= n; i++) {
        if (d[i] == 0) {
            if (i != s)
                out << "-1 ";
            else
                out << "0 ";
        } else
            out << d[i] << " ";
    }
    return 0;
}