Cod sursa(job #1884518)

Utilizator Dupree7FMI Ciobanu Andrei Dupree7 Data 18 februarie 2017 20:50:36
Problema BFS - Parcurgere in latime Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <queue>
#include <vector>
using namespace std;

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


int N, M, X;
int d[100001], viz[100001];
vector<int> v[100000];

void bfs(int nod)
{
    int i, x;
    queue<int> q;

    q.push(nod);
    viz[nod] = 1;

    while(!q.empty())
    {
        x = q.front();
        q.pop();

        for(int oth = 0; oth < int(v[x].size()); oth++)
            if(!viz[v[x][oth]])
                {
                viz[v[x][oth]] = 1;
                d[v[x][oth]] = d[x] + 1;
                q.push(v[x][oth]);
                }
    }

    for(i = 1; i < N + 1; i++)
        if(viz[i] == 0)
        {
            if(i == X)
                g << "0 ";
            else
                g << "-1 ";
        }
        else
            g << d[i] << " ";
}

int main()
{
    int i;

    f >> N >> M >> X;

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

    bfs(X);

    return 0;
}