Pagini recente » Cod sursa (job #532119) | Cod sursa (job #3264104) | Cod sursa (job #2356839) | Cod sursa (job #1914363) | Cod sursa (job #2850277)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int MAX_SIZE = 100005;
vector<int> graph[MAX_SIZE];
int distances[MAX_SIZE];
queue<int> positions;
void BFS() {
while (!positions.empty()) {
int currentPeak = positions.front();
int size = graph[currentPeak].size();
for (int i = 0; i < size; ++i) {
int nextPeak = graph[currentPeak][i];
if (distances[nextPeak] == -1) {
distances[nextPeak] = distances[currentPeak] + 1;
positions.push(nextPeak);
}
}
positions.pop();
}
}
int main() {
int peaks, arches, startPeak;
fin >> peaks >> arches >> startPeak;
for (int i = 1; i <= arches; ++i) {
int start, end;
fin >> start >> end;
if (start != end) {
graph[start].push_back(end);
}
}
positions.push(startPeak);
for (int i = 1; i <= peaks; ++i) {
distances[i] = -1;
if (i == startPeak) {
distances[i] = 0;
}
}
BFS();
for (int i = 1; i <= peaks; ++i) {
fout << distances[i] << " ";
}
return 0;
}
/*
5 5 2
2 3
2 1
4 1
3 4
1 5
1 0 1 2 2
Teste:
exemplu:
5 7 2
1 2
2 1
2 2
3 2
2 5
5 3
4 5
-> 1 0 2 -1 1
5 4 1
1 2
2 3
3 5
5 4
-> 0 1 2 4 3
5 3 1
1 2
2 3
3 5
-> 0 1 2 -1 3
5 1 1
1 2
-> 0 1 -1 -1 -1
5 20 3
1 2
1 3
1 4
1 5
2 1
2 3
2 4
2 5
3 1
3 2
3 4
3 5
4 1
4 2
4 3
4 5
5 1
5 2
5 3
5 4
-> 1 1 0 1 1
*/