Cod sursa(job #1559093)

Utilizator Mr.DoomRaul Ignatus Mr.Doom Data 30 decembrie 2015 01:27:51
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <fstream>
#include <queue>
#include <bitset>
using namespace std;

ifstream is("bfs.in");
ofstream os("bfs.out");

void Read();
void Bfs(int x);

vector<vector<int> > g;
vector<int> d;
queue<int> q;
bitset<100001> v;
int n, m, s;

int main()
{
    Read();
    Bfs(s);
    for ( int i = 1; i <= n; ++i )
    {
        if ( d[i] == 0 && i != s )
            os << -1 << ' ';
        else
            os << d[i] << ' ';
    }
    is.close();
    os.close();
    return 0;
}

void Read()
{
    int x, y;
    is >> n >> m >> s;
    g.resize(n + 1);
    d.resize(n + 1);
    for ( int i = 1; i <= m; ++i )
    {
        is >> x >> y;
        g[x].push_back(y);
    }
}

void Bfs(int x)
{
    int y;
    d[x] = 0;
    v[x] = 1;
    q.push(x);
    while ( !q.empty() )
    {
        y = q.front();
        q.pop();
        for ( const auto &t : g[y] )
            if ( !v[t] )
            {
                v[t] = true;
                d[t] = d[y] + 1;
                q.push(t);
            }
    }
}