Cod sursa(job #3121514)

Utilizator rutakateIvanovici Vlad rutakate Data 13 aprilie 2023 16:26:04
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>

using namespace std;

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

vector<int> a[100000];

int main()
{
    int n, s;
    fin >> n;
    int margini;
    fin >> margini;
    fin >> s;
    while(margini--) {
        int x, y;
        fin >> x >> y;
        a[x].push_back(y);
        //a[y].push_back(x);
    }
    int vizitat[n + 1] = {0};
    int d[n + 1], p[n + 1];
    for(int i = 1; i <= n; ++i) {
        d[i] = -1;
    }
    vizitat[s] = 1;
    d[s] = 0;
    p[s] = -1;
    queue<int> q;
    q.push(s);
    while(!q.empty()) {
        int v = q.front();
        q.pop();
        for(int u: a[v]) {
            if(!vizitat[u]) {
                vizitat[u] = 1;
                q.push(u);
                d[u] = d[v] + 1;
                p[u] = v;
            }
        }
    }
    for(int i = 1; i <= n; ++i) {

        fout << i << " ";
    }
    fout << endl;
    for(int i = 1; i <= n; ++i) {

        fout << d[i] << " ";
    }
    fout << endl;
    /*int dest = 5;
    vector<int> path;
    if(vizitat[dest] == 0) {
        fout << " -1" << " ";
    }
    else {

        int x = dest;
        while(x != -1) {
            path.push_back(x);
            x = p[x];
        }
        reverse(path.begin(), path.end());
    }
    for(int i = 0; i < path.size(); ++i) {
        fout << path[i] << " ";
    }
    fout << endl;*/
    return 0;
}