Cod sursa(job #2467632)

Utilizator Senth30Denis-Florin Cringanu Senth30 Data 4 octombrie 2019 18:51:11
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 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 <pair <int, 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] = -1;
    for(int i = 1; i <= M; i++){
        Read(x); Read(y);
        Gph[x].push_back(y);
    }
}

int main(){

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

    read();

    Q.push(make_pair(S, 0));
    while(!Q.empty()){
        int x = Q.front().first;
        int y = Q.front().second;
        for(int i = 0; i < Gph[x].size(); i++){
            if(ans[Gph[x][i]] == -1){
                ans[Gph[x][i]] = y + 1;
                Q.push(make_pair(Gph[x][i], y + 1));
            }
        }
        Q.pop();
    }

    for(int i = 1; i <= N; i++)
        printf("%d ", ans[i]);

    return 0;
}