Pagini recente » Cod sursa (job #2775208) | Cod sursa (job #2764556) | Cod sursa (job #143762) | Cod sursa (job #1748669) | Cod sursa (job #2587500)
#include<vector>
#include<queue>
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void add_edge(vector<int> g_list[], int u, int v)
{
g_list[u].push_back(v);
}
void print_g(vector<int> g_list[], int V)
{
for (int v = 1; v <= V; ++v)
{
cout << "\n Vertex : " << v<<endl;
for (auto x : g_list[v])
cout << " " << x ;
}
}
#define nr_el 100000
int M ; //Number of edges
int N; //Number of nodes
int s; //Starting node
vector <int> graph[nr_el];
int dist[200005];
void BEFEU(int st)
{
queue<int> Q;
Q.push(st);
dist[st] = 0;
while(!Q.empty())
{
int cur = Q.front();
Q.pop();
for(unsigned int i = 0; i < graph[cur].size(); ++i)
{
int vecin = graph[cur][i];
if(vecin == st){
continue;
}
if(!dist[vecin])
{
dist[vecin] = dist[cur] + 1;
Q.push(vecin);
}
}
}
}
int main()
{
ifstream file;
file.open("bfs.in");
file >> N >> M >> s;
int x ,y ; //Two vertices
while(M){
file >> x >> y;
add_edge(graph , x , y);
--M;
}
file.close();
ofstream out_file;
out_file.open("bfs.out");
//print_g(graph , N);
BEFEU(s);
for(int i = 1 ; i <= N ; ++i){
if(i == s && dist[i] == 0){
out_file<<dist[i] << " ";
}
else if(i != s && dist[i] == 0){
out_file<<dist[i] - 1<< " ";
}
else{
out_file<<dist[i] << " ";
}
}
out_file.close();
return 0;
}