Cod sursa(job #2665946)

Utilizator CoakazeRotaru Catalin Coakaze Data 31 octombrie 2020 15:16:18
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.84 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

vector<int> gr[100005];
int n, m, s;
int viz[100005], d[100005];

int main()
{
    ifstream f("bfs.in");
    ofstream g("bfs.out");
    int x, y;
    f>>n>>m>>s;
    for(int i = 0; i < m; i++)
    {
        f>>x>>y;
        gr[x].push_back(y);
    }
    queue<int> q;
    q.push(s);
    viz[s] = 1;
    while(!q.empty())
    {
        int new_s = q.front();
        q.pop();
        for(auto v : gr[new_s])
        {
            if(viz[v] == 0)
            {
                viz[v] = 1;
                q.push(v);
                d[v] = d[new_s] + 1;
            }
        }
    }
    for(int i = 1; i <= n; i++)
        if(viz[i] == 0)
            g<<"-1"<<" ";
        else
            g<<d[i]<<" ";
    return 0;
}