Cod sursa(job #2422025)

Utilizator MateiAruxandeiMateiStefan MateiAruxandei Data 16 mai 2019 21:51:15
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <fstream>
#include <queue>

using namespace std;

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

vector<int> Muchii[100005];

int cost[1000005];

void BFS(int nod){
    queue<int> q;
    q.push(nod);
    cost[nod] = 0;
    while(!q.empty()){
        int nd = q.front();
        q.pop();
        for(int i = 0; i < Muchii[nd].size(); ++i){
            if(cost[Muchii[nd][i]] == -1){
                cost[Muchii[nd][i]] = cost[nd] + 1;
                q.push(Muchii[nd][i]);
            }
        }
    }
}

int main()
{
    int n, m, s;
    fin >> n >> m >> s;

    for(int i = 1; i <= n; ++i)
        cost[i] = -1;

    for(int i = 1; i <= m; ++i){
        int x, y;
        fin >> x >> y;

        Muchii[x].push_back(y);
    }

    BFS(s);

    for(int i = 1; i <= n; ++i)
        fout << cost[i] << ' ';
    fout << '\n';
    return 0;
}