Cod sursa(job #2355114)

Utilizator Tudor_Trasculescu123Tudor Trasculescu Tudor_Trasculescu123 Data 25 februarie 2019 20:26:43
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("bfs.in") ;
ofstream fout("bfs.out") ;

int n , m , x , y , s  , c[100005] , visited[100005] ;
struct MakePer
{
    vector <int> v ;
};
MakePer a[100005] ;

void bfs(int s)
{
    queue <int> Q ;
    Q.push({s}) ;

    while(!Q.empty())
    {
        x = Q.front() ;
        for(vector<int>::iterator it = a[x].v.begin(); it != a[x].v.end(); it ++)
        {
            int y = *it ;
            if(visited[y] == 0 && y != s)
            {
               visited[y] = visited[x] + 1 ;
               Q.push(y) ;
            }
        }
        Q.pop() ;
    }
}
int main()
{
    fin >> n >> m >> s ;
    for(int i=1; i<=m; i++)
    {
        fin >> x >> y ;
        a[x].v.push_back(y) ;
    }
    bfs(s) ;
    for(int i=1; i<=n; i++)
    {
       if(visited[i] == 0 && i != s)
           fout << "-1" << " ";
       else
           fout << visited[i] << " ";
    }

    return 0;
}