Cod sursa(job #1907473)

Utilizator MailatMailat Radu Mailat Data 6 martie 2017 19:26:31
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#include <vector>
#include <stdio.h>
#include <string.h>
#define maxn 100010
using namespace std;

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

int N, M, s;
vector <int>A[maxn];
int G[maxn], S[maxn], Cost[maxn];

void bfs(int nod) {
    memset(Cost, -1, sizeof(Cost));

    int L = 1;
    S[L] = nod;
    Cost[nod] = 0;

    for(int i=1; i<=L; i++) {
        for(int j=0; j < G[S[i]]; j++) {
            if(Cost[A[S[i]][j]] == -1) {
                S[++L] = A[S[i]][j];
                Cost[S[L]] = Cost[S[i]] + 1;
            }
        }
    }
}

int main()
{
    fin >> N >> M >> s;
    int x, y;
    for(int i=0; i<M; i++) {
        fin >> x >> y;
        A[x].push_back(y);
    }
    for(int i=1; i<=N; i++) {
        G[i] = A[i].size();
    }
    bfs(s);
    for(int i=1; i<=N; i++) fout << Cost[i] << " ";
    return 0;
}