Cod sursa(job #1774122)

Utilizator RobertSSamoilescu Robert RobertS Data 8 octombrie 2016 16:32:04
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

int N, M, S;
int const MAX_N = 100001;
bool vis[MAX_N];
int cost[MAX_N];

vector<int> graph[MAX_N];

void BFS(int node, int depth) {

	stack<int> st;
	vis[node] = true;
	st.push(node);

	while (!st.empty()) {
		int top = st.top();
		st.pop();

		for (size_t i = 0; i < graph[top].size(); i++) {
			int next_node = graph[top][i];
			if (!vis[next_node]) {
				vis[next_node] = true;
				st.push(next_node);
				cost[next_node] = cost[top] + 1;
			}
		}
	}

}

int main() {

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

	fin >> N >> M >> S;

	for (int i = 0; i < M; i++) {
		int n1, n2;
		fin >> n1 >> n2;
		graph[n1].push_back(n2);

	} 


	BFS(S, 0);

	for (int i = 1; i <= N; i++) {
		if (vis[i])
			fout << cost[i] << " ";
		else 
			fout << -1 << " ";

	}

	fin.close();
	fout.close();

	return 0;	
}