Cod sursa(job #991681)

Utilizator StickmanLazar Alexandru Stickman Data 31 august 2013 11:11:04
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.83 kb
#include <vector>
#include <fstream>
#include <iostream>

using namespace std;

vector <int> v[100001];
int c[100001], d[100001], cost[100001];
int n,m,s;

void bfs()
{
    int i,j,k;
    cost[s]=0;
    j=1;
    c[0]=s;
    for(i=0; i<j; i++)
        for(k=0; k<d[c[i]]; k++)
            if(cost[v[c[i]][k]]==-1)
            {
                c[j]=v[c[i]][k];
                cost[c[j]]=cost[c[i]]+1;
                j++;
            }
}

int main()
{
    int i,x,y;
    ifstream in("bfs.in");
    ofstream out("bfs.out");
    in>>n>>m>>s;
    for(i=0; i<m; i++)
    {
        in>>x>>y;
        v[x].push_back(y);
    }
    in.close();
    for(i=1; i<=n; i++)
    {
        d[i]=v[i].size();
        cost[i]=-1;
    }

    bfs();
    for(i=1; i<=n; i++)
        out<<cost[i]<<" ";

    return 0;
}