Cod sursa(job #2346182)

Utilizator VarticeanNicolae Varticean Varticean Data 17 februarie 2019 12:43:18
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>
using namespace std;

typedef struct nod
{
    int val;
    nod* next;
} *graf;

graf lta[100100];
int N,M,cost[100100],start;
bitset<100100>vis;
queue<int>q;

void add(graf &a, int v)
{
    graf b = new nod;
    b->val = v;
    b->next = a;
    a=b;
}
void bfs()
{
    q.push(start);
    vis[start]=1;
    while(!q.empty())
    {
        int head = q.front();
        q.pop();
        for(graf x = lta[head]; x!=NULL; x=x->next)
        {
            if(!vis[x->val])
            {
                vis[x->val]=1;
                cost[x->val]= cost[head]+1;
                q.push(x->val);
            }
        }
    }

}

int main()
{
    ios::sync_with_stdio(0);
    ifstream in("bfs.in");
    ofstream out("bfs.out");
    in >> N >> M >> start;
    int x,y;
    for(int i=1; i<=M; i++)
    {
        in >> x >> y;
        add(lta[x],y);
    }
    bfs();
    for(int i=1; i<=N   ; i++) if(vis[i]) out<<cost[i]<< ' ';
        else out << -1 << ' ';


    return 0;
}