Cod sursa(job #2256335)

Utilizator DjpaulmcIonescu Andrei Paul Djpaulmc Data 8 octombrie 2018 15:39:19
Problema BFS - Parcurgere in latime Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

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

int N,M,S,t;
int const Nmax = 10000;
vector <int> G[Nmax];
int Cost[Nmax],V[Nmax],P[Nmax];

void Read()
{
    fin>>N>>M>>S;
    for(int i = 1 ; i <= M ; ++i)
    {
        int x,y;
        fin>>x>>y;

        G[x].push_back(y);
    }
}
void BFS(int nod)
{
    memset(Cost, -1, sizeof(Cost));

    t = 1;
    Cost[nod] = 0;

    V[t] = nod;

    for(int i = 1 ; i <= t ; i++)
        for(int j = 0 ; j < P[V[i]]; j++)
            if(Cost[G[V[i]][j]] == -1)
            {
                V[++t] =G[V[i]][j];
                Cost[V[t]] = Cost[V[i]] + 1;
            }
}

int main()
{


    Read();
    for(int i = 1; i <= N; i++)
        P[i] = G[i].size();




    BFS(S);
    for(int i = 1 ; i <= N; i++)
        fout<<Cost[i]<<" ";
    return 0;
}