Cod sursa(job #1463597)

Utilizator Tester01tester Tester01 Data 21 iulie 2015 12:26:13
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cmath>
using namespace std; 
ifstream cin("bfs.in");
ofstream cout("bfs.out");
#define Nmax 100013
  
class cell {
  public : 
    int node;
    cell *prev;
    cell (int a, cell *l) {node=a; prev=l;};
 };
       
 class DirectedGraph {
     private : 
               cell *adj[Nmax];
               bool used[Nmax];
			   int d[Nmax];
               
     public : 
              void addEdge(int a,int b){
                 cell *aux = new cell(b,adj[a]); adj[a]=aux; 
              }
               
			  vector <int> BFS(int source,int nodes){
			    queue <int> Q;
			    vector <int> sol;
			    for (int i=1;i<=nodes;++i) d[i]=Nmax;
			    d[source]=0;
			    Q.push(source);
			    while(!Q.empty()){
			    	cell *son = adj[Q.front()];
			    	int father = Q.front();
			    	Q.pop();
			    	for (;son;son=son->prev){
			    	   	if (!used[son->node]){
			    	   		used[son->node]^=1;
			    	   		Q.push(son->node);
			    	   	}
			    	   	d[son->node] = min ( d[son->node], d[father] + 1); 
			    	   }
			    }
			    for (int i=1;i<=nodes;++i) 
			       if (d[i]!=Nmax) sol.push_back(d[i]); 
			               else sol.push_back(-1);
		         return sol;
		      }
 } Graph;
  
int n,m,a,b,source;
int main(void) {
 cin>>n>>m>>source;
 while(m--) {
    cin>>a>>b;
    Graph.addEdge(a,b);
    }
 vector <int>  sol = Graph.BFS(source,n);
 vector <int>::iterator it;
 for (it=sol.begin();it!=sol.end();++it)
    cout<<*it<<" ";
 return 0;
}