Cod sursa(job #2220475)

Utilizator dragos.galeteanu2001Dragos Iulian dragos.galeteanu2001 Data 11 iulie 2018 20:29:38
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <cstdio>
#include <cstdlib>

using namespace std;

int n, m, s, c[100001], lg[100001];
int *a[100001];
bool checked[100001];

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

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

	for (int i = 1; i <= n; ++i) {
		a[i] = (int *)realloc(a[i], sizeof(int));
		a[i][0] = 0;
	}

	while (m--) {
		int x, y;
		scanf("%d%d", &x, &y);

		++a[x][0];
		a[x] = (int *)realloc(a[x], (a[x][0] + 1) * sizeof(int));
		a[x][a[x][0]] = y;
	}

	int back_side, front_side, distance = 0;

	lg[s] = 0;
	checked[s] = 1;

	c[1] = s;
	back_side = front_side = 1;

	while (back_side <= front_side) {
		int x = c[back_side++];
		for (int i = 1; i <= a[x][0]; ++i)
			if (!checked[a[x][i]]) {
				lg[a[x][i]] = lg[x] + 1;
				checked[a[x][i]] = 1;
				c[++front_side] = a[x][i];
			}
	}

	for (int i = 1; i <= n; ++i) {
		if (i != s && !lg[i]) printf("%d ", -1);
		else printf("%d ", lg[i]);
	}

	fclose(in);
	fclose(out);

    return 0;
}