Cod sursa(job #2256439)

Utilizator b10nd3Oana Mancu b10nd3 Data 8 octombrie 2018 17:16:34
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.82 kb
#include<iostream>
#include<fstream>
#include<queue>
 
using namespace std;
 
#define MAX_NODES 100001
 
vector <int> graph[MAX_NODES];
queue <int> aux;
int checked[MAX_NODES], cost[MAX_NODES];
 
int main(){
ifstream in; ofstream out;
in.open("bfs.in"); out.open("bfs.out");
out.clear();
 
int n,m,s,x,y,i; 
vector<int>::iterator it;
 
in>>n>>m>>s;
for(i=1;i<=m;i++){
  in>>x>>y;
  graph[x].push_back(y);
}
 
aux.push(s); checked[s]=1; 
while(!aux.empty()){
   x=aux.front(); aux.pop();
   for(it=graph[x].begin(); it!=graph[x].end();it++){
       if(checked[*it]==0) {
           checked[*it]=1; 
           cost[*it]=cost[x]+1;
           aux.push(*it);
       }
   }
}
 
for(i=1;i<=n;i++)
    if(checked[i]==1) out<<cost[i]<<" ";
    else out<<"-1 ";
 
in.close(); out.close();
return 0;
}