Cod sursa(job #1503921)

Utilizator moise_alexandruMoise Alexandru moise_alexandru Data 17 octombrie 2015 09:04:42
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string.h>
#include <queue>
using namespace std;
ifstream in("bfs.in");
ofstream out("bfs.out");

const int maxn = 100005;
vector <int> g[maxn];
queue <int> q;
int dist[maxn];

int main()
{
    int n, m, s;
    in >> n >> m >> s;
    for(int i = 1; i <= m; i++)
    {
        int x, y;
        in >> x >> y;
        g[x].push_back(y);
    }
    memset(dist, -1, sizeof(dist)); /// marcheaza peste tot -1
    q.push(s);
    dist[s] = 0;
    while(!q.empty())
    {
        int p = q.front();
        q.pop();
        for(unsigned int i = 0; i < g[p].size(); i++)
        {
            if(dist[g[p][i]] == -1)
            {
                q.push(g[p][i]);
                dist[g[p][i]] = dist[p] + 1;
            }
        }
    }

    for(int i = 1; i <= n; i++)
        out << dist[i] << " ";
    out << "\n";
    return 0;
}