Cod sursa(job #3156449)

Utilizator Alexandru_1_9Radu Alexandru-Mihail Alexandru_1_9 Data 11 octombrie 2023 17:14:44
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
using namespace std;

ifstream f("bfs.in");
ofstream g("bfs.out");

const int NMAX = 100000;
vector <int> G[NMAX + 1];
int vis[NMAX + 1];
int d[NMAX+1];

void BFS(int x) {

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

}

int main()
{
	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 (d[i]==0 && s==i)
            g<<0<<" ";
        else if (d[i]==0)
            g<<-1<<" ";
        else g<<d[i]<<" ";

    return 0;
    }

}