Cod sursa(job #1597493)

Utilizator sebii_cSebastian Claici sebii_c Data 12 februarie 2016 00:40:51
Problema BFS - Parcurgere in latime Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <fstream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <queue>

using namespace std;

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

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;
	unordered_set<T> visited;
	queue<T> q;

	result[node] = 0;
	q.push(node);
	visited.insert(node);
	while (!q.empty()) {
	    auto x = q.front(); q.pop();

	    for (auto next : neighbors[x]) {
		if (visited.find(next) == visited.end()) {
		    visited.insert(next);
		    result[next] = result[x] + 1;
		    q.push(next);
		}
	    }
	}

	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;
}