Cod sursa(job #2706863)

Utilizator UnknownPercentageBuca Mihnea-Vicentiu UnknownPercentage Data 15 februarie 2021 22:09:52
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.58 kb
#include <bits/stdc++.h>
 
using namespace std;
 
ifstream fin("bfs.in");
ofstream fout("bfs.out");

vector <int> g[100001];
bitset <100001> v;
int d[100001];

void bfs(int st){
	queue <int> q;

	q.push(st), v[st] = 1;

	while(!q.empty()){
		int k = q.front();
		q.pop();
		for(int x : g[k])
			if(!v[x]) v[x] = 1, d[x] = d[k] + 1, q.push(x);
	}
}

int main(){
	int N, M, X;
	fin >> N >> M >> X;
	while(M--){
		int x, y;
		fin >> x >> y;
		g[x].emplace_back(y);
	}

	bfs(X);

	for(int i = 1;i <= N;i++)
		if(v[i]) fout << d[i] << " ";
		else fout << "-1 ";
}