Cod sursa(job #2256165)

Utilizator HerddexJinga Tudor Herddex Data 8 octombrie 2018 09:15:14
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <fstream>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");

struct Node
{
    int node;
    Node *next;
} *G[100001];

int N;

void bfs(int S)
{
    int Q[100001];
    int dist[100001];
    for(int i=1; i<=N; i++)
        dist[i] = -1;


    int first = 0;
    int last = 0;
    dist[S] = 0;
    Q[first] = S;

    while(first<=last)
    {
        for(Node *p = G[Q[first]]; p!=0; p = p->next)
        {
            if(dist[p->node] == -1)
            {
                dist[p->node] = dist[Q[first]] + 1;
                last++;
                Q[last] = p->node;
            }
        }
        first++;
    }

    for(int i=1; i<=N; i++)
        fout << dist[i] << ' ';
}

int main()
{
    int M, S;
    fin >> N >> M >> S;

    while(M)
    {
        int x, y;
        fin >> x >> y;
        Node *p = new Node;
        p->node = y;
        p->next = G[x];
        G[x] = p;
        M--;
    }

    bfs(S);

    fin.close();
    fout.close();
    return 0;
}