Cod sursa(job #1144205)

Utilizator ciubakkaCiobotarasu Vlad ciubakka Data 16 martie 2014 19:27:24
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
int n,m,s;
vector<bool> viz;
vector<int> cost;

typedef struct nod
{
    int nd;
    nod *next;
} *pnod;

pnod v[100010];

void add(pnod &root, int vecin)
{
    pnod p;
    p = new nod;
    p->nd=vecin;
    p->next=root;
    root=p;
}

void create()
{
    f>>n>>m>>s;
    viz.resize(n+1,0);
    cost.resize(n+1,-1);
    int a,b;
    while(f>>a>>b)
    {
        add(v[a],b);
    }
    f.close();
}

void check()
{
    int nod, vrf;
    queue<int> q;

    viz[s]=1;
    cost[s]=0;
    for( pnod p=v[s];p!=NULL;p=p->next)
     {nod=p->nd;
    if(nod!=s)
    {
      q.push(nod);
      viz[nod]=1;
      cost[nod]=1;
    }}
    while(!q.empty())
    {
        nod=q.front();
        q.pop();
        for( pnod p=v[nod];p!=NULL;p=p->next)
            {vrf=p->nd;
            if(!viz[vrf])
            {
                q.push(vrf);
                viz[vrf]=1;
                cost[vrf]=cost[nod]+1;
            }}
    }
}

void show()
{   int i;
    for(i=1;i<=n;i++)
        g<<cost[i]<<" ";
    g.close();
}

int main()
{
    create();
    check();
    show();
    return 0;
}