Cod sursa(job #2664193)

Utilizator georgeblanarBlanar George georgeblanar Data 28 octombrie 2020 09:20:02
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>

using namespace std;

#define maxn 100010

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

int n, m, start;
vector<int> adj[maxn];
int cost[maxn];
list<int> queue;

void bfs(int node)
{
    queue.push_back(node);
    fill_n(cost, maxn, -1);
    cost[node] = 0;


    while(!queue.empty()) {
        cout << '\n';

        int curr = queue.front();
        queue.pop_front();

        for(auto it = adj[curr].begin(); it != adj[curr].end(); it++) {
            if(cost[*it] == -1) {
                queue.push_back(*it);
                cost[*it] = cost[curr] + 1;
            }
        }
    }
}
int main()
{
    f >> n >> m >> start;

    for(int i = 0; i < m; i++) {
        int a, b;
        f >> a >> b;
        adj[a].push_back(b);
    }

    bfs(start);

    for(int i = 1; i <= n; i++) {
        g << cost[i] << " ";
    }

    return 0;
}