Cod sursa(job #2635023)

Utilizator irimia_alexIrimia Alex irimia_alex Data 12 iulie 2020 23:32:57
Problema BFS - Parcurgere in latime Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <stdio.h>
#include <vector>
#include <queue>
#define NMAX 100000

using namespace std;

FILE* fin, * fout;

vector<int> g[NMAX + 1];
int n, m, s;

void BFS() {
    int len[NMAX + 1] = { 0 };
    deque<pair<int,int>> q;
    q.push_back({ s,0 });
    int viz[NMAX + 1] = { 0 };
    for (int i = 1;i <= n;++i)
        len[i] = -1;
    while (!q.empty()) {
        auto x = q.front();
        q.pop_front();
        viz[x.first] = 1;
        if (len[x.first] == -1)
            len[x.first] = x.second;
        for (auto y : g[x.first]) {
            if (!viz[y]) {
                q.push_back({ y,x.second + 1 });
            }
        }
    }
    for (int i = 1;i <= n;++i)
        fprintf(fout,"%i ", len[i]);
}

int main()
{
    fin = fopen("bfs.in", "r");
    fout = fopen("bfs.out", "w");

    fscanf(fin, "%i %i %i", &n, &m, &s);
    while (m--) {
        int x, y;
        fscanf(fin, "%i %i", &x, &y);
        g[x].push_back(y);
    }

    BFS();
  
    return 0;
}