Cod sursa(job #2667509)

Utilizator tudosemihaitudose mihai tudosemihai Data 3 noiembrie 2020 15:44:44
Problema BFS - Parcurgere in latime Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;

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

int n, m, s;
int dist[100005];
bool found;

vector<int> g[100005];
vector<int> bfs;

int main() {

    in >> n >> m >> s;

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

    bfs.push_back(s);
    int j = 0;
    found = true;
    while(found)
    {
        found = false;
        int u = bfs[j];
        for(int i = 0; i < g[u].size(); i++)
        {
            int next = g[u][i];
            if(next == s)
                found = true;
            else if(dist[next]==0) {
                bfs.push_back(next);
                dist[next] = dist[u] + 1;
                found = true;
            }
        }
        j++;
    }
    for(int i = 1; i <= n; i++)
    {
            if(dist[i]==0 && s!=i)
                out << -1 << " ";
            else
                out << dist[i] << " ";

    }





    return 0;
}