Cod sursa(job #3125840)

Utilizator vladp1324Vlad Pasare vladp1324 Data 4 mai 2023 17:37:00
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 100000
#define INF 100001

using namespace std;

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

int n, m, d[NMAX + 1];
bool ver[NMAX + 1];
vector <int> v[NMAX + 1];

void bfs(int s){
    for (int i = 1; i <= n; i++)
        d[i] = INF;
    queue <int> q;
    q.push(s);
    ver[s] = true;
    d[s] = 0;
    while(!q.empty()) {
        int f = q.front();
        q.pop();
        for (int j = 0; j < v[f].size(); j++) {
            if (not ver[v[f][j]]) {
                ver[v[f][j]] = true;
                d[v[f][j]] = d[f] + 1;
                q.push(v[f][j]);
            }
        }
    }
    for (int i = 1; i <= n; i++)
        if (d[i] == INF)
            d[i] = -1;
}

int main()
{
    int s;
    fin >> n >> m >> s;
    for(int i = 1; i <= m; i++) {
        int x, y;
        fin >> x >> y;
        v[x].push_back(y);
    }
    bfs(s);
    for (int i = 1; i <= n; i++)
        fout << d[i] << ' ';
    return 0;
}