Cod sursa(job #2669247)

Utilizator bogdan2604Bogdan Dumitrescu bogdan2604 Data 6 noiembrie 2020 16:22:30
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream f("bfs.in");
ofstream g("bfs.out");

int n,m,inc,x,y,a,b,i,val[100001];
vector <vector<int>> mat;
queue <int> q;

void BFS()
{
    q.push(inc);
    val[inc] = 1;
    while(!q.empty())
    {
        a = q.front();
        q.pop();
        for(i = 0; i < mat[a].size(); ++ i)
        {
            b = mat[a][i];
            if(!val[b])
            {
                val[b] = val[a] + 1;
                q.push(b);
            }
        }
    }
}

int main()
{
    f >> n >> m >> inc;
    mat.resize(n + 1);
    while(m --)
    {
        f >> x >> y;
        mat[x].push_back(y);
    }
    BFS();
    for(i = 1; i <= n; ++ i, g << ' ')
        if(val[i] == 1)
            g << 0;
        else if(!val[i])
            g << -1;
        else
            g << val[i] - 1;
    return 0;
}