Pagini recente » Cod sursa (job #2974242) | Cod sursa (job #1170408) | Cod sursa (job #3215136) | Utilizatori inregistrati la PreOJI 2017 | Cod sursa (job #3275615)
#include <iostream>
#include <queue>
#include <bitset>
#define maxSize 100001
using namespace std;
vector<vector<int>> readAdjacencyList(int nodes, int edges, bool isDirected = false) {
vector<vector<int>> adjList(nodes + 1);
for (int i = 0; i < edges; i++) {
int x, y;
cin >> x >> y;
adjList[x].push_back(y);
if (!isDirected) {
adjList[y].push_back(x);
}
}
return adjList;
}
vector<int> breadthFirstSearch(const vector<vector<int>>& adjList, int start) {
bitset<maxSize> marked;
marked[start] = true;
vector<int> distance;
distance.resize(adjList.size(), -1);
distance[start] = 0;
queue<int> q;
q.push(start);
while (!q.empty()) {
int head = q.front();
q.pop();
for (auto node : adjList[head]) {
if (!marked[node]) {
distance[node] = distance[head] + 1;
marked[node] = true;
q.push(node);
}
}
}
return distance;
}
int main() {
int nodes, edges, start;
cin >> nodes >> edges >> start;
auto distance = breadthFirstSearch(readAdjacencyList(nodes, edges), start);
for (auto elem : distance) {
cout << elem << " ";
}
cout << endl;
return 0;
}