Cod sursa(job #1591722)

Utilizator tudormaximTudor Maxim tudormaxim Data 6 februarie 2016 16:55:17
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int nmax = 1e5+5;
vector <int> g[nmax];
int dist[nmax];

void bfs(int start)
{
    vector <int> :: iterator son;
    queue <int> q;
    int dad;
    q.push(start);
    dist[start]=0;
    while(!q.empty())
    {
        dad=q.front();
        q.pop();
        for(son=g[dad].begin(); son!=g[dad].end(); son++)
            if(dist[*son]==-1)
            {
                dist[*son]=dist[dad]+1;
                q.push(*son);
            }
    }
}
int main()
{
    ios_base::sync_with_stdio(false);
    int n, m, x, y, s, i;
    fin >> n >> m >> s;
    while(m--)
    {
        fin >> x >> y;
        g[x].push_back(y);
    }
    for(i=1; i<=n; i++)
        dist[i]=-1;
    bfs(s);
    for(i=1; i<=n; i++)
        fout << dist[i] << " ";
    fin.close();
    fout.close();
    return 0;
}