Cod sursa(job #1597483)

Utilizator sebii_cSebastian Claici sebii_c Data 12 februarie 2016 00:32:46
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <unordered_map>
#include <unordered_set>
#include <vector>

using namespace std;

template <class T>
class graph {
    unordered_map<T, vector<T>> neighbors;
    unordered_set<T> nodes;

    void breadth_first_search(T node, unordered_map<T, int>& depth, int d) {
	static unordered_set<T> visited;
	
	if (visited.find(node) != visited.end()) {
	    return;
	}
	
	visited.insert(node);
	depth[node] = d;
	for (auto next : neighbors[node]) {
	    breadth_first_search(next, depth, d + 1);
	}
    }

public:
    template <class Iterator>
    graph(Iterator begin, Iterator end):
	nodes(begin, end) {}

    void add_edge(T src, T dst) {
	neighbors[src].push_back(dst);
    }

    unordered_map<T, int> breadth_first_search(T node) {
	unordered_map<T, int> result;
	breadth_first_search(node, result, 0);

	for (auto other : nodes) {
	    if (other != node && result[other] == 0)
		result[other] = -1;
	}

	return result;
    }
};

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

    int n, m, s;
    fin >> n >> m >> s;
    vector<int> nodes;
    for (int i = 1; i <= n; ++i) {
	nodes.push_back(i);
    }

    graph<int> G(nodes.begin(), nodes.end());
    for (int i = 0; i < m; ++i) {
	int src, dst;
	fin >> src >> dst;
	G.add_edge(src, dst);
    }

    auto result = G.breadth_first_search(s);
    for (auto x : nodes) {
	fout << result[x] << " ";
    }
    fout << endl;
    
    return 0;
}