Cod sursa(job #2026279)

Utilizator PondorastiAlex Turcanu Pondorasti Data 24 septembrie 2017 10:38:15
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.85 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
const int NMAX = 100000;
int n, m, s, x, y, i, cost[NMAX + 5];
vector <int> g[NMAX + 5];
queue<int> q;
void BFS(int s);
int main() {
    ifstream cin("bfs.in");
    ofstream cout("bfs.out");
    cin >> n >> m >> s;
    for(i = 1; i <= m; ++i) {
        cin >> x >> y;
        g[x].push_back(y);
    }
    BFS(s);
    for(i = 1; i <= n; ++i)
        cout << cost[i] - 1 << " ";
    cout << "\n";
    return 0;
}
void BFS(int s) {
    q.push(s);
    cost[s] = 1;
    while (!q.empty()) {
        int first = q.front();
        q.pop();
        vector <int>::iterator it;
        for(it = g[first].begin(); it < g[first].end(); ++it) {
            if(cost[*it] == 0) {
                cost[*it] += (cost[first] + 1);
                q.push(*it);
            }
        }
    }
}