Cod sursa(job #3156537)

Utilizator Serban09Baesu Serban Serban09 Data 11 octombrie 2023 18:39:01
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <iostream>
#include<vector>
#include<queue>
#include<fstream>
using namespace std;

const int nmax = 1000000;
vector<int> g[nmax+1];
int vis[nmax+1], d[nmax+1];

void BFS(int x)
{
    queue<int>q;
    q.push(x);
    vis[x] = 1;
    d[x] = 0;
    while(!q.empty()){
        x = q.front();
        q.pop();
        for(auto next : g[x]){
            if(!vis[next]){
                q.push(next);
                vis[next] = 1;
                d[next] = d[x] + 1;
            }
        }
    }
}


int main()
{
    ifstream f("bfs.in");
    ofstream h("bfs.out");
    int n, m, s;
    f>>n>>m>>s;
    for(int i=1; i<=m; i++){
        int x, y;
        f>>x>>y;
        g[x].push_back(y);
    }
    BFS(s);
    for(int i=1; i<=n; i++){
        if(i != s && d[i] == 0)
            h<<-1<<" ";
        else h<<d[i]<<" ";
    }

    return 0;
}