Cod sursa(job #2301810)

Utilizator vranceanu.andi2014Vranceanu Andi vranceanu.andi2014 Data 13 decembrie 2018 15:53:20
Problema BFS - Parcurgere in latime Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define LGMAX 100001
using namespace std;

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

queue<int> c;
vector<int> g[LGMAX];
bool uz[LGMAX];
int distanta[LGMAX];
int n, m, s;

void bfs(int k);

int main()
{
    int x, y;
    fin >> n >> m >> s;
    for (int i=0; i<m; i++)
    {
        fin >> x >> y;
        g[x].push_back(y);
    }
    for (int i=1; i<=n; i++)
        distanta[i] = -1;
    bfs(s);
    for (int i=1; i<=n; i++)
    {
        fout << distanta[i] << " ";
    }
    fout << '\n';
    return 0;
}

void bfs(int k)
{
    int st, dr, x, nivel = 0;
    st = dr = k;
    c.push(k);
    uz[k] = true;
    while(!c.empty())
    {
        while (!c.empty() && c.front() != dr)
        {
            st = c.front();
            c.pop();
            uz[st] = true;
            distanta[st] = nivel;
            for (unsigned int i=0; i<g[st].size(); i++)
            {
                if (!uz[g[st][i]])
                {
                    c.push(g[st][i]);
                }
            }
        }
        x = c.front();
        c.pop();
        uz[x] = true;
        distanta[x] = nivel;
        for (unsigned int i=0; i<g[x].size(); i++)
            {
                if (!uz[g[x][i]])
                {
                    c.push(g[x][i]);
                }
            }
        if (!c.empty())
        {
            st = c.front();
            dr = c.back();
        }
        nivel++;
    }
}