Cod sursa(job #2007086)

Utilizator epermesterNagy Edward epermester Data 1 august 2017 20:06:56
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 0.84 kb
#include<fstream>
#include<queue>
#include<iterator>
using namespace std;

struct csucs {
	vector<int>szomszedok;
	int tavolsag = -1;
};

int main() {
	ifstream in("bfs.in");
	int N, M, S;
	in >> N >> M >> S;
	csucs* csucsok = new csucs[N];
	for (int i = 0;i < M;++i) {
		int honnan, hova;
		in >> honnan >> hova;
		csucsok[honnan-1].szomszedok.push_back(hova-1);
	}

	csucsok[S - 1].tavolsag = 0;
	queue<int> q;
	S--;
	while(true)
	{
		if(!q.empty()) q.pop();
		for (vector<int>::iterator it = csucsok[S].szomszedok.begin();
			it != csucsok[S].szomszedok.end();++it)
			if (csucsok[*it].tavolsag==-1) {
				q.push(*it);
				csucsok[*it].tavolsag = csucsok[S].tavolsag + 1;
			}
		if (q.empty()) break;
		S = q.back();
	}

	ofstream out("bfs.out");
	for (int i = 0;i < N;++i) {
		out << csucsok[i].tavolsag << " ";
	}
}