Cod sursa(job #2461918)

Utilizator ivddabDabelea Ioana-Viviana ivddab Data 26 septembrie 2019 15:43:53
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <fstream>
#include <queue>
#include <vector>
#define NM 1000003
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
int n,m,s,i,x,y;
int ap[NM];
bool fr[NM];
vector < int > a[NM];
queue < int > q;
int main()
{
    f>>n>>m>>s;
    for(i=1;i<=m;i++) { f>>x>>y; a[x].push_back(y); }
    q.push(s); fr[s]=1; ap[s]=0;
    while(!q.empty()){
        x=q.front();
        for(i=0;i<a[x].size();i++){
            y=a[x][i];
            if(fr[y]==0){
                ap[y]=ap[x]+1; q.push(y); fr[y]=1;
            }
        }
        q.pop();
    }
    for(i=1;i<=n;i++){
       if(i==s) g<<0<<' ';
         else{
            if(ap[i]==0) g<<-1<<' ';
              else       g<<ap[i]<<' ';
         }
    }
    return 0;
}