Cod sursa(job #2083713)

Utilizator Teodor.mTeodor Marchitan Teodor.m Data 8 decembrie 2017 00:36:51
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>
using namespace std;

typedef long long int ll;
typedef long double ld;

inline void debugMode() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    #ifndef ONLINE_JUDGE
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);
    #endif // ONLINE_JUDGE
}
inline void PrintYes() { cout << "Yes"; }
inline void PrintNo() { cout << "No"; }

const double eps = 1e-7;
const int Nmax = 1e5 + 5;

vector < int > G[Nmax];
bool viz[Nmax];
int dist[Nmax];

void BFS(int nod)
{
    queue< int > q;
    viz[nod] = true;
    q.push(nod);

    while(q.size()) {
        nod = q.front();
        q.pop();

        for(auto it: G[nod]) {
            if(viz[it] == false) {
                viz[it] = true;
                q.push(it);
                dist[it] = dist[nod] + 1;
            }
        }
    }
}

int main()
{
	debugMode();

    int n, m, nod;
    cin >> n >> m >> nod;

    for(int j = 0; j < m; ++j) {
        int x, y;
        cin >> x >> y;
        G[x - 1].push_back(y - 1);
    }

    BFS(nod - 1);

    for(int i = 0; i < n; ++i)
        if((i != nod - 1) && dist[i] == 0)
            cout << "-1 ";
        else
            cout << dist[i] << " ";

	return 0;
}