Cod sursa(job #3165123)

Utilizator mdayAyabakti Muhammed Melih mday Data 5 noiembrie 2023 14:50:23
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <fstream>
#include <vector>
#include <queue>

std::ifstream fin("bfs.in");
std::ofstream fout("bfs.out");

const int nMax = 1e5;

std::vector<std::vector<int>> graf;
std::queue<int> q;

int cost[nMax];

void bfs(int nod) {
    q.push(nod);
    cost[nod] = 1;
    while(!q.empty()) {
	nod = q.front();
	q.pop();
	for(int next : graf[nod])
	    if(cost[next] == 0) {
		q.push(next);
		cost[next] = cost[nod] + 1;
	    }
    }
}

int main() {
    int n, m, k;

    fin >> n >> m >> k;

    k--;

    graf.assign(n, std::vector<int>());
    
    for(int i = 0; i < m; ++i) {
	int x, y;
	fin >> x >> y;
	x--, y--;
	graf[x].push_back(y);
    }

    bfs(k);

    for(int i = 0; i < n; ++i)
	fout << cost[i] - 1 << ' ';

    graf.clear();
    fin.close();
    fout.close();
    return 0;
}