Cod sursa(job #1917017)

Utilizator TendoHackerBogdan Blaga TendoHacker Data 9 martie 2017 10:55:35
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m ,s;
vector<int> adjList[100007];
int dist[100007];

void read()
{
    int x,y;
    fin >> n >> m >> s;

    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        adjList[x].push_back(y);
    }

    for(int i = 1; i <= n; i++)
    {
        dist[i] = -1;
    }
}

void BFS()
{
    queue<int> q;

    dist[s] = 0;

    q.push(s);

    while(!q.empty())
    {
        int v = q.front();
        q.pop();
        int g = adjList[v].size();
        for(int i = 0; i < g;i++)
        {
            if(dist[adjList[v][i]] == -1)
            {
                dist[adjList[v][i]] = dist[v] + 1;
                q.push(adjList[v][i]);
            }
        }
    }
}

int main()
{
    read();
    BFS();
    for(int i = 1;i <= n; i++)
    {
        fout << dist[i] << " ";
    }
    return 0;
}