Cod sursa(job #2008500)

Utilizator andreistanStan Andrei andreistan Data 6 august 2017 18:02:50
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>
using namespace std;

ifstream f("bfs.in");
ofstream g("bfs.out");
int N, M, S, viz[100001], cost[100001];

//BFS latime graf orientat

struct nod
{
    int x;
    nod *leg;
};
nod *v[100001];

void add(nod *&dest, int val)
{
    nod *p;
    p = new nod;
    p -> x = val;
    p -> leg = dest;
    dest = p;
}

void citiregraf()
{
    f >> N >> M >> S;
    while(M--)
    {
        int x, y;
        f >> x >> y;
        add(v[x], y);
    }
}

void afis()
{
    for(int i = 1; i <= N; i++)
        if(cost[i] == 0 && i != S)
            g << "-1 ";
        else
            g << cost[i] << ' ';
}

void latime(int x)
{
    int p, u, cr, c[100001];
    p = u = 1;
    c[u] = x;
    viz[x] = 1;
    while(p <= u)
    {
        nod *q;
        cr = c[p++];
        for(q = v[cr]; q != NULL; q = q->leg)
            if(!viz[q->x])
            {
                c[++u] = q->x;
                viz[q->x] = 1;
                cost[q->x] = cost[cr] + 1;
            }
    }
}

int main()
{
    citiregraf();
    latime(S);
    afis();
    return 0;
}