Cod sursa(job #2510686)

Utilizator twiliamioanToader Wiliam Ioan twiliamioan Data 17 decembrie 2019 09:40:17
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <queue>
#include <fstream>
#include <vector>
using namespace std;
bool viz[100001];
vector<int> la[100001];
int cost[100001];
queue<int> bf;
int main() {
    int n, m;
    ifstream fin("bfs.in");
    ofstream fout("bfs.out");
    //citire
    int st;
    fin >> n >> m >> st;
    int a, b;
    for(int i = 1; i <= m; i++) {

        fin >> a >> b;
        la[a].push_back(b);
        //la[b].push_back(a);
    }
    for(int i = 0; i <= n; i++) cost[i] = -1;
    bf.push(st);
    cost[st] = 0;
    while(!bf.empty()) {
        int x = bf.front();
        int cst_x = cost[x];
        bf.pop();

        //cout << x << " ";
        viz[x] = true;

        for(int i = 0; i < la[x].size(); i++) {
            if(!viz[la[x][i]]) {
                bf.push(la[x][i]);
                cost[la[x][i]] = cst_x + 1;
            }
        }
    }
    //cout << endl;
    for(int i = 1; i <= n; i++) {
        fout << cost[i] << " ";
    }
    fin.close();
    fout.close();
    return 0;
}