Cod sursa(job #2682709)

Utilizator teofilotopeniTeofil teofilotopeni Data 9 decembrie 2020 13:10:45
Problema BFS - Parcurgere in latime Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <iostream>
#include <deque>
using namespace std;

//  BFS

struct Node {
    int minim = -1, n = 0;
    deque<int> from;
};

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

    nodes[s].minim = 0;
    int start = 0, last = 1, total = 1;
    int sorted[n + 1];
    sorted[0] = s;

    while (start < last) {  //  Cat timp mai adaugam elemente
        while (start < last) {  //  Elementele cu un rang inainte
            for (i = 0; i < nodes[sorted[start]].n; i++) {  //  Parcurgem toate elementele care ajung in cel actual
                int nr = nodes[sorted[start]].from[i];
                if (nodes[nr].minim < 0) {  //  Daca elementul nu a mai fost gasit
                    nodes[nr].minim = nodes[sorted[start]].minim + 1;
                    sorted[total] = nr;
                    total++;
                }
            }
            start++;
        }
        last = total;
    }
    for (i = 1; i <= n; i++)
        printf("%d ", nodes[i].minim);
}