Cod sursa(job #1736125)

Utilizator AllenWalkerAllen Walker AllenWalker Data 1 august 2016 11:16:27
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

vector <int> Lista[100002];
queue <int> Q;
int dist[100002], viz[100002];
int n,m,s;

void BFS(int x)
{
    viz[x]=-1;
    Q.push(x);
    while(!Q.empty())
    {
        x=Q.front();
        Q.pop();
        for(int i=0; i<Lista[x].size(); i++)
            if(!viz[Lista[x][i]])
            {
                viz[Lista[x][i]]=1;
                Q.push(Lista[x][i]);
                dist[Lista[x][i]]=dist[x]+1;
            }
    }
}

int main()
{
    in>>n>>m>>s;
    int x,y;
    for(int i=1; i<=n; i++)
        dist[i]=-1;
    dist[s]=0;
    for(int i=1; i<=m; i++)
    {
        in>>x>>y;
        Lista[x].push_back(y);
    }

    BFS(s);
    for(int i=1; i<=n; i++)
        out<<dist[i]<<' ';

    return 0;
}