Cod sursa(job #2489688)

Utilizator mirceatlxhaha haha mirceatlx Data 9 noiembrie 2019 11:06:36
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define NMAX 100005
using namespace std;

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

vector <int> ListAdiacenta[NMAX];
queue <int> Q;
int Cost[NMAX], Vec[NMAX];
int Node, N, M;

void BFS(int start)
{
    memset(Cost,-1,sizeof(Cost));
    Q.push(start);
    Cost[start] = 0;
    while(!Q.empty())
    {
        int curr = Q.front();
        for(int i = 0; i < Vec[curr]; i++)
            if(Cost[ListAdiacenta[curr][i]] == -1)
            {
                Q.push(ListAdiacenta[curr][i]);
                Cost[ListAdiacenta[curr][i]] = Cost[curr] + 1;
            }
        Q.pop();
    }
}

int main()
{   
    int x, y;
    fin >> N >> M >> Node;
    for(int i = 1; i <= M; i++)
    {
        fin >> x >> y;
        ListAdiacenta[x].push_back(y);
    }
    for(int i = 1; i <= N; i++)
        Vec[i] = ListAdiacenta[i].size();
    BFS(Node);
    for(int i = 1; i <= N; i++)
        fout << Cost[i] << " ";
    fout << "\n";
    fin.close();
    fout.close();
    return 0;
}