Cod sursa(job #2634654)

Utilizator BogdanFarcasBogdan Farcas BogdanFarcas Data 11 iulie 2020 21:04:08
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <queue>
#include <cstring>

using namespace std;

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

const int N=1e5+1;

struct nod
{
    int nr;
    nod *st,*dr;
};

queue<int>q;
nod *v[N];
int cost[N];
int n,m,s,x,y;

void bfs(int start)
{
    memset(cost,-1,sizeof(cost));
    q.push(start);
    cost[start]=0;
    while(!q.empty())
    {
        nod *p=v[q.front()];
        while(p!=NULL)
        {
            if(cost[p->nr]==-1)
            {
                q.push(p->nr);
                cost[p->nr]=cost[q.front()]+1;
            }
            p=p->st;
        }
        q.pop();
    }
}

int main()
{
    fin>>n>>m>>s;
    for(int i=1;i<=m;i++)
    {
        fin>>x>>y;
        if(v[x]==NULL)
        {
            v[x]=new nod;
            v[x]->nr=y;
            v[x]->dr=NULL;
            v[x]->st=NULL;
        }
        else
        {
            nod *t=new nod;
            t->nr=y;
            t->dr=NULL;
            v[x]->dr=t;
            t->st=v[x];
            v[x]=t;
        }
    }
    bfs(s);
    for(int i=1;i<=n;i++)
    {
        fout<<cost[i]<<" ";
    }
    return 0;
}