Cod sursa(job #1359283)

Utilizator cristian.enciuCristian Enciu cristian.enciu Data 24 februarie 2015 21:55:36
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.77 kb
#include<stdio.h>
#include<vector>
#include<queue>
#include<string.h>

using namespace std;

vector<vector<int> > nodes;
int n, m, s;
int v[100010];
queue<int> q;

int main()
{
	freopen("bfs.in", "r", stdin);
	freopen("bfs.out", "w", stdout);

	scanf("%d%d%d", &n, &m, &s);

	memset(v, -1, sizeof(v));

	for(int i = 0 ; i <= n ; ++i) {
		vector<int> x;
		nodes.push_back(x);
	}

	for(int i = 0 ; i < m ; ++i) {
		int x, y;
		scanf("%d%d", &x, &y);

		nodes[x].push_back(y);
	}

	q.push(s);
	v[s] = 0;

	while(!q.empty()) {
		int x = q.front();
		q.pop();
		int nv = v[x] + 1;

		for(int i : nodes[x]) {
			if(v[i] == -1) {
				v[i] = nv;
				q.push(i);
			}
		}
	}

	for(int i = 1 ; i <= n ; ++i) {
		printf("%d ", v[i]);
	}

	return 0;
}