Pagini recente » Cod sursa (job #2110810) | Cod sursa (job #2652991) | Cod sursa (job #910099) | Cod sursa (job #346202) | Cod sursa (job #2529582)
#include<fstream>
#include<iostream>
#include<list>
#include<cstring>
#include<vector>
using namespace std;
ifstream f("bfs.in");
ofstream o("bfs.out");
struct node{
int y, cost;
};
class Graph{
list<node>*Adj;
public:Graph(int n){
Adj=new list<node>[n];
}
public:int addEdge(int x, int y){
Adj[x].push_back({y, 0});
return 0;
}
public:int bfs(int s, int n){
int c;
list<node>::iterator i;
vector<int>cost(n, -1);
list<int>q;
q.push_back(s);
cost[s]=0;
while(!q.empty()){
c=q.front();
q.pop_front();
for(i=Adj[c].begin(); i!=Adj[c].end(); i++){
if(cost[(*i).y]==-1){
q.push_back((*i).y);
cost[(*i).y]=cost[c]+1;
}
}
}
for(int i=1;i<n;i++){
o<<cost[i]<<" ";
}
return 0;
}
};
int main(){
int n, m, s, x, y;
f>>n>>m>>s;
Graph g(n+1);
for(int i=0;i<m;i++){
f>>x>>y;
g.addEdge(x, y);
}
g.bfs(s, n+1);
}