Cod sursa(job #2636844)

Utilizator bogdangabriel99Dumitru Bogdan bogdangabriel99 Data 20 iulie 2020 13:45:16
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>
using namespace std;

int const maxSize = 200002;

queue<int>que;
vector<int> adjacency[maxSize];
vector<int> dist(maxSize, 0);
int visited[maxSize], n, m, s;

ifstream f("bfs.in");
ofstream h("bfs.out");

void Read()
{
	f >> n >> m >>s;
	for (int i = 1; i <= m; i++)
	{
		int x, y;
		f >> x >> y;
		adjacency[x].push_back(y);
	}
}

void BFS()
{
	visited[s] = 1;
	que.push(s);

	while (!que.empty())
	{
		int node = que.front();
		int length = adjacency[node].size();
		que.pop();
		for (int i = 0; i < length; i++)
		{
			if (!visited[adjacency[node][i]])
			{	
				dist[adjacency[node][i]] = dist[node] + 1;
				visited[adjacency[node][i]] = 1;
				que.push(adjacency[node][i]);
			}
		}
	}
}

void Print()
{   /* Print the nodes that are not visited (in case I look at this 2-3 years from now)*/
	bool printed_something = false;
	for (int i = 1; i <= n; i++)
	{
		if (dist[i] == 0 && i != s)
			h << "-1" << ' ';
		else h << dist[i]<<' ';
	}
}

int main()
{
	Read();
	BFS();
	Print();
	return 0;
}