Cod sursa(job #2774358)

Utilizator SerbaP123Popescu Serban SerbaP123 Data 11 septembrie 2021 13:00:23
Problema BFS - Parcurgere in latime Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
using namespace std;

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

#define cin in
#define cout out
#define pb push_back
#define f first
#define s second
#define FOR(i, a, b) for(int i = a; i <= b; ++i)

typedef long long ll;
typedef long double lld;
typedef unsigned long long ull;

const lld pi = 3.14159265358979323846;
const ll mod = 1000000007;
const ll nmax = 1e5;

ll n, m, x, y, z, i, j, k, l, r, p;
ll v[nmax + 1];
//ll a[nmax + 1];
//ll b[nmax + 1];
ll ans = 0, cnt = 0, maxim;
string s, t;
vector <ll> edges[nmax + 1];
queue <ll> q;

void BFS(){
	ll node;
	while(!q.empty()){
		node = q.front();
		q.pop();
		FOR(i, 0, edges[node].size() - 1){
			if(v[edges[node][i]] == -1){
				q.push(edges[node][i]);
				v[edges[node][i]] = v[node] + 1;
			}
		}
	}
}

void solve(int tc = 0){
    cin >> n >> m >> p;
	while(m--){
		cin >> x >> y;
		edges[x].pb(y);
	}
	memset(v, -1, sizeof(v));
	q.push(p);
	v[p] = 0;
	BFS();
	FOR(i, 1, n){
		cout << v[i] << " ";
	}
}

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int tc = 1;
	//cin >> tc;
	FOR(i, 1, tc)
		solve(i);
}