Cod sursa(job #1701745)

Utilizator vladc096Vlad Cincean vladc096 Data 13 mai 2016 23:21:07
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <queue>

using namespace std;

class DiGraph {
private:
	map<int, vector<int>> outbounds;
	map<int, vector<int>> inbounds;
	int N; // no. of vertices
	int M; // no. of edges

public:
	DiGraph() {};
	DiGraph(string filename) {
		int s, t;
		ifstream f(filename);
		f >> N; f >> M;
		f >> s; //...
		for (int i = 0; i < M; i++) {
			f >> s; f >> t;
			this->addEdge(s, t);
		}
		f.close();
	}

	int getN() {
		return this->N;
	}

	map<int, vector<int>> parseNout() {
		return outbounds;
	}
	
	map<int, vector<int>> parseNin() {
		return inbounds;
	}

private:
	void addEdge(int s, int t) {
		outbounds[s].push_back(t);
		inbounds[t].push_back(s);
	}
};

class BFS {
private:
	map<int, int> dist; // dist from s to each vertex
	int s; // the source vertex
	DiGraph* g; // the graph

public:
	BFS(string filename) {
		this->g = new DiGraph(filename);
		ifstream f(filename);
		f >> s; f >> s; f >> s;
		f.close();
		this->doBFS();
	}

	map<int, int> getDistances() {
		return this->dist;
	}

	int getN() {
		return this->g->getN();
	}

private:
	void doBFS() {
		queue<int> q;
		map<int, bool> visited;
		int x;
		for (int i = 1; i <= this->g->getN() && i != this->s; i++)
			visited[i] = false;
		visited[s] = true;
		q.push(s);
		this->dist[s] = 0;
		while (!q.empty()) {
			x = q.front();
			q.pop();
			for (int y : this->g->parseNout()[x]) {
				if (visited[y] == false) {
					q.push(y);
					visited[y] = true;
					this->dist[y] = this->dist[x] + 1;
				}
			}
		}
		int i = 1;
		while (i < this->g->getN())
			if (visited[i] == false)
				dist[i] = -1;
	}
};

int main() {
	BFS bfs("bfs.in");
	ofstream f("bfs.out");
	map<int, int> dist = bfs.getDistances();
	for (int i = 1; i <= bfs.getN(); i++) {
		f << dist[i] << " ";
	}
	f.close();
}