Pagini recente » Cod sursa (job #1041350) | Cod sursa (job #1753806) | Cod sursa (job #3248712) | Cod sursa (job #445741) | Cod sursa (job #3150637)
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int MAX_LENGTH = 100000;
vector<int> graph[MAX_LENGTH + 1];
int minDistance[MAX_LENGTH + 1];
int main() {
int nodesNr, archesNr, startNode;
fin >> nodesNr >> archesNr >> startNode;
for (int arch = 1; arch <= archesNr; ++arch) {
int start, end;
fin >> start >> end;
graph[start].push_back(end);
}
int queue[MAX_LENGTH + 1] = {0}, queueLen = 0, len = 1, nodesMarked[MAX_LENGTH + 1] = {0};
nodesMarked[startNode] = 1;
for (vector<int>::iterator it = graph[startNode].begin(); it < graph[startNode].end(); ++it) {
if (nodesMarked[*it] == 0) {
nodesMarked[*it] = 1;
queue[++queueLen] = *it;
minDistance[*it] = len;
}
}
bool nextNodesAccess = 1;
int start = 1;
while (nextNodesAccess == 1) {
nextNodesAccess = 0;
++len;
int auxQueueLen = queueLen;
for (int i = start; i <= queueLen; ++i) {
for (vector<int>::iterator j = graph[queue[i]].begin(); j < graph[queue[i]].end(); ++j) {
if (nodesMarked[*j] == 0) {
nodesMarked[*j] = 1;
nextNodesAccess = 1;
queue[++auxQueueLen] = *j;
minDistance[*j] = len;
}
}
}
start = queueLen + 1;
queueLen = auxQueueLen;
}
for (int i = 1; i <= nodesNr; ++i) {
if (minDistance[i] == 0 && i != startNode) {
fout << "-1 ";
} else {
fout << minDistance[i] << ' ';
}
}
return 0;
}
/*
2 2 1
1 2
1 1
=>
0 1
5 7 2
1 2
2 1
2 2
3 2
2 5
5 3
4 5
=>
1 0 2 -1 1
3 2 2
1 3
1 2
=>
-1 0 -1
6 5 1
1 2
1 3
2 4
4 5
5 6
=>
0 1 1 2 3 4
*/