Mai intai trebuie sa te autentifici.

Cod sursa(job #1794325)

Utilizator tonisnakesBoar Antonio tonisnakes Data 1 noiembrie 2016 10:44:20
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.79 kb
#include <iostream> // practice source
#include <fstream>
#include <vector>
#define MAXN 100005
using namespace std;

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

int n, m, l, st;
vector<int> a[MAXN];
int g[MAXN], s[MAXN], cost[MAXN];

void bfs (int nod) 
{
	for (int i = 1; i <= n; ++i){
		cost[i] = -1;
	}
	
	l = 1;
	cost[nod] = 0;
	s[l] = nod;
	
	for (int i = 1; i <= l; ++i) {
		for (int j = 0; j < g[s[i]]; ++j) {
			if (cost[a[s[i]][j]] == -1) {
				s[++l] = a[s[i]][j];
				cost[s[l]] = cost[s[i]] + 1;
			}
		}
	}
}

int main () 
{
	int x, y;
	fin >> n >> m >> st;
	
	for (int i = 1; i <= m; ++i) {
		fin >> x >> y;
		a[x].push_back(y);
	}
	
	for (int i = 1; i <= n; ++i) {
		g[i] = a[i].size();
	}
	
	bfs(st);
	
	for (int i = 1; i <= n; ++i) {
		fout << cost[i] << " ";
	}
	
	return 0;
}