Cod sursa(job #3145387)

Utilizator daristyleBejan Darius-Ramon daristyle Data 15 august 2023 12:17:55
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int N_MAX = 1e5;
vector<int> adj[N_MAX];
int dist[N_MAX]{};

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

	dist[start] = 1;
	q.push(start);

	while(!q.empty()){
		int node = q.front();

		for(auto neighbour: adj[node])
			if(!dist[neighbour]){
				dist[neighbour] = dist[node] + 1;
				q.push(neighbour);
			}

		q.pop();
	}
}

int main(){
	int nodes, edges, start, a, b;
	fin >> nodes >> edges >> start;
	--start;
	for(int i = 0; i < edges; ++i){
		fin >> a >> b;
		--a;
		--b;

		adj[a].push_back(b);
	}

	bfs(start);

	for(int node = 0; node < nodes; ++node)
		fout << dist[node] - 1 << ' ';
	fout.put('\n');

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