Pagini recente » Cod sursa (job #1105885) | Cod sursa (job #2574262) | Monitorul de evaluare | Statistici Roland Boldesco (Roland_aseugfo) | Cod sursa (job #1701745)
#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();
}