Pagini recente » Cod sursa (job #643572) | Cod sursa (job #814909) | Cod sursa (job #821071) | Cod sursa (job #286478) | Cod sursa (job #447572)
Cod sursa(job #447572)
/*
* File: main.cpp
* Author: Johnny
*
* Created on April 29, 2010, 1:53 AM
*/
#include <stdlib.h>
#include <fstream>
#include <list>
#include <queue>
using namespace std;
/*
*
*/
int n, m, s;
int main(int argc, char** argv) {
fstream fin("bfs.in", ios_base::in);
fin >> n >> m >> s;
--s;
list<int> rel[n];
int x, y;
for (int i = 0; i < m; ++i) {
fin >> x >> y;
rel[x - 1].push_back(y - 1);
}
fin.close();
bool was[n];
int dist[n];
for (int i = 0; i < n; ++i) {
was[i] = false;
dist[i] = -1;
}
fstream fout("bfs.out", ios_base::out);
queue<int> q;
q.push(s);
q.push(-1); // Signalling a new depth
was[s] = true;
dist[s] = 0;
int d = 1;
while (q.size() > 1) {
x = q.front();
q.pop();
if (x == -1) {
++d;
q.push(-1);
}
else
for (list<int>::const_iterator it = rel[x].begin(); it != rel[x].end(); ++it)
if (!was[*it]) {
q.push(*it);
was[*it] = true;
dist[*it] = d;
}
}
for (int i = 0; i < n; ++i)
fout << dist[i] << ' ';
fout.close();
return (EXIT_SUCCESS);
}