Cod sursa(job #2651321)

Utilizator grigorut_octavianGrigorut Dominic Octavian grigorut_octavian Data 22 septembrie 2020 11:16:36
Problema BFS - Parcurgere in latime Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <bits/stdc++.h>

using namespace std;

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

struct ant
{
    int ord, varf;
};

struct nod
{
    int val;
    nod *next;
};
nod *l[100001];

queue<ant> q;

int n,m,s;

void adauga(nod *&p, int x)
{
    if(p==NULL)
    {
        p=new nod;
        p->val=x;
        p->next=NULL;
    }
    else
    {
        nod *q=p;
        while(q->next!=NULL)
            q=q->next;
        nod *w=new nod;
        w->val=x;
        w->next=NULL;
        q->next=w;
    }
}

void goleste(queue<ant> q)
{
    while(!q.empty())
        q.pop();
}

int  rezolva(queue<ant> q, int s, int f, nod *l[])
{
    if(s==f) return 0;
    nod *p=l[f];
    if(!q.empty()) goleste(q);
    while(p)
    {
        ant x;
        x.ord=1;
        x.varf=p->val;
        q.push(x);
        p=p->next;
    }
    while(!q.empty())
    {
        ant a=q.front();
        q.pop();
        if(a.varf==s)
            return a.ord;
        else
        {
            nod *w=l[a.varf];
            while(w)
            {
                ant x;
                x.ord=a.ord+1;
                x.varf=w->val;
                q.push(x);
                w=w->next;
            }

        }
    }
    return -1;
}

int main()
{
    fin>>n>>m>>s;
    for(int i=1; i<=m; i++)
    {
        int x,y;
        fin>>x>>y;
       if(x!=y) adauga(l[y],x);
    }
    for(int i=1;i<=n;i++)
    {
        fout<<rezolva(q,s,i,l)<<' ';
    }
    return 0;
}