Cod sursa(job #2467623)

Utilizator Senth30Denis-Florin Cringanu Senth30 Data 4 octombrie 2019 18:34:23
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>
#define MAX 131072

using namespace std;
const int NMAX = 100010;

FILE *IN;

int N, M, S;
int ans[NMAX];
vector <int> Gph[NMAX];
queue <int> Q;

int pos, sign;
char f[MAX];

inline void Read(int &nr){
    sign = 0;
    nr = 0;
    while(f[pos] < '0' || f[pos] > '9'){
        if(f[pos] == '-') sign = 1;
        pos++;
        if(pos == MAX)
            fread(f, MAX, 1, IN), pos = 0;
    }
    while(f[pos] >= '0' && f[pos] <= '9'){
        nr = 10 * nr + f[pos++] - '0';
        if(pos == MAX)
            fread(f, MAX, 1, IN), pos = 0;
    }
    if(sign) nr =- nr;
}

void read(){
    int x, y;
    Read(N); Read(M); Read(S);
    for(int i = 1; i <= N; i++) ans[i] = 2e9;
    for(int i = 1; i <= M; i++){
        Read(x); Read(y);
        Gph[x].push_back(y);
    }
}

int BFS(int node, int val){
    ans[node] = min(val, ans[node]);
    for(int i = 0; i < Gph[node].size(); i++)
        if(ans[Gph[node][i]] == 2e9)
            BFS(Gph[node][i], val + 1);
}

int main(){

    IN = fopen("bfs.in", "r");
    freopen("bfs.out", "w", stdout);

    read();

    BFS(S, 0);
    for(int i = 1; i <= N; i++){
        if(ans[i] != 2e9) printf("%d ", ans[i]);
        else printf("-1 ");
    }

    return 0;
}