Cod sursa(job #2620357)

Utilizator mex7Alexandru Valentin mex7 Data 28 mai 2020 19:13:33
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");
vector<int> lista[100010];
int freq[100010][2];

void bfs(int start) {
    queue<pair<int, int> > q;
    q.push(make_pair(start, 0));
    freq[start][0] = 1;
    freq[start][1] = 0;

    while (!q.empty()) {
        pair<int, int> top = q.front();
        q.pop();

        for (int i = 0; i < lista[top.first].size(); i++)
            if (!freq[lista[top.first][i]][0]) {
                q.push(make_pair(lista[top.first][i], top.second + 1));
                freq[lista[top.first][i]][0] = 1;
                freq[lista[top.first][i]][1] = top.second + 1;
            }
    }
}

int main() {
    int n, m, s;
    int x, y;

    fin >> n >> m >> s;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y;
        lista[x].push_back(y);
    }

    bfs(s);


    for (int i = 1; i <= n; i++)
        if (freq[i][0] == 0)
            fout << -1 << " ";
        else
            fout << freq[i][1] << " ";

    return 0;
}