Pagini recente » Cod sursa (job #2157405) | Cod sursa (job #282555) | Cod sursa (job #2168437) | Cod sursa (job #530574) | Cod sursa (job #1383276)
#include<vector>
#include<algorithm>
#include<fstream>
#include<iostream>
#include<queue>
#include<set>
using namespace std;
vector<int> adj[100004];
queue<pair<int, int> > Q;
void clear( queue<pair<int, int> > &q )
{
queue<pair<int,int> > empty;
swap( q, empty );
}
vector<int> visited(100004, -1);
void bfs(int start) {
visited[start] = 0;
int depth = 1;
int v_size = adj[start].size();
for(int i = 0; i < v_size; ++i) {
Q.push(make_pair(adj[start][i], depth));
visited[adj[start][i]] = 1;
}
// cout << "\n start:" << start << "\n";
while(!Q.empty()) {
pair<int, int> el = Q.front(); Q.pop();
int currentNode = el.first;
int currentDepth = el.second;
// cout << " cN:" << currentNode << " cD:" << currentDepth << "\n";
v_size = adj[currentNode].size();
for(int i = 0; i < v_size; ++i) {
if(visited[adj[currentNode][i]] == -1){
Q.push(make_pair(adj[currentNode][i], currentDepth + 1));
visited[adj[currentNode][i]] = currentDepth + 1;
}
}
}
}
int main() {
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int N,M,S; fin >> N >> M >> S;
for(int i = 0; i < M; ++i) {
int from,to; fin >> from >> to;
adj[from].push_back(to);
}
bfs(S);
fout << visited[1] << " ";
for(int i = 2; i <= N; ++i) {
fout << " " << visited[i];
}
fout << "\n";
return 0;
}