Cod sursa(job #2290262)

Utilizator ArsuhArsene Vlad Arsuh Data 26 noiembrie 2018 10:48:35
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

#define nmax 1000005

vector<int> V[nmax];
int n, m, s, dist[nmax], viz[nmax];

void citire()
{
    ifstream f ("bfs.in");

    f>>n>>m>>s;
    for(int i=0; i<m; i++)
    {
        int x, y;
        f>>x>>y;
        V[x].push_back(y);
    }
}

void initialize()
{
    for(int i=0; i<=n; i++)
        dist[i]=-1;
}

void bfs()
{
    queue<int> q;
    q.push(s);
    dist[s]=0;
    viz[s]=1;

    int nr=1;
    while(!q.empty())
    {
        bool ok=false;
        for(auto x:V[q.front()])
            if(!viz[x])
            {
                q.push(x);
                if(dist[x]==-1)
                    dist[x]=nr;
                ok=true;
            }
        if(!ok)
            nr++;
        q.pop();
    }
}


void afisare()
{
    ofstream g("bfs.out");
    for(int i=1; i<=n; i++)
            g<<dist[i]<<' ';
}
int main()
{

    citire();
    initialize();
    bfs();
    afisare();

    return 0;
}