Cod sursa(job #2550924)

Utilizator rexlcdTenea Mihai rexlcd Data 19 februarie 2020 11:44:37
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

vector < int > v[100002];
queue < int > q;

int cost[100002];

int main() {
    ifstream f("bfs.in");
    ofstream g("bfs.out");
    int n, m, s;
    f >> n >> m >> s;
    for(int i = 1; i <= m; i++) {
        int x, y; f >> x >> y;
        v[x].push_back(y);
    }
    
    memset(cost, -1, sizeof(cost));
    cost[s] = 0;
    q.push(s);
    while(!q.empty()) {
        int x = q.front();
        q.pop();
        
        for(int i = 0; i < v[x].size(); i++)
            if(cost[v[x][i]] == -1) {
                q.push(v[x][i]);
                cost[v[x][i]] = cost[x] + 1;
            }
    }
    
    for(int i = 1; i <= n; i++)
        g << cost[i] << ' ';
    g << '\n';
    f.close();
    g.close();
    return 0;
}