Cod sursa(job #2422327)

Utilizator test666014test test test666014 Data 18 mai 2019 13:18:06
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <iomanip>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <queue>
#include <memory>
#include <algorithm>
#include <map>
#include <stack>
#include <vector>
#include <string>
#include <cstring>
#include <functional>
using namespace std;

int n, m, s, ok[100100], d[100100];
vector<int> g[100100];

void bfs(int x) {
    queue<int> q;
    q.push(x);
    ok[x] = true;
    for (int i = 1; i <= n; ++i) d[i] = -1;
    d[x] = 0;
    while (!q.empty()) {
        x = q.front();
        q.pop();
        for (auto y : g[x]) {
            if (!ok[y]) {
                ok[y] = true;
                d[y] = d[x] + 1;
                q.push(y);
            }
        }
    }
}

int main() {
    freopen("bfs.in","r",stdin);
    freopen("bfs.out","w",stdout);
    int x, y;
    scanf("%d %d %d", &n, &m, &s);
    for (int i = 0; i < m; ++i) {
        scanf("%d %d", &x, &y);
        g[x].push_back(y);
    }
    bfs(s);
    for (int i = 1; i <= n; ++i) {
        printf("%d ", d[i]);
    }
    return 0;
}