Cod sursa(job #844340)

Utilizator TripluYOlteanu Costin TripluY Data 29 decembrie 2012 00:44:24
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

vector <int> vecin[100000];
queue <int> to_expand;
int lungime[100000],cost[1000000];
int n,m,s;

inline void citire()
{
    ifstream f("bfs.in");
    f >> n >> m >> s;
    --s;

    int x,y,i;
    for(i = 0; i < m; i++)
    {
        f >> x >> y;
        --x;--y;
        vecin[x].push_back(y);
    }
    f.close();

    for(i = 0; i < n; i++)
        lungime[i] = vecin[i].size();
}

inline void afisare()
{
    ofstream g("bfs.out");
    for(int i = 0; i < n; i++)
        g << cost[i] << " ";
    g.close();
}

inline void bfs()
{
    to_expand.push(s);
    cost[s] = 0;

    int x;
        while(!to_expand.empty())
        {
            for(int i = 0; i < lungime[to_expand.front()]; ++i)
            {
                if(cost[vecin[to_expand.front()][i]] == -1)
                {
                    x = vecin[to_expand.front()][i];
                    to_expand.push(x);
                    cost[x] = cost[to_expand.front()] + 1;
                }
            }
        to_expand.pop();
        }
}

int main()
{

    citire();

    for(int i = 0; i < n;i++)
        cost[i] = -1;

    bfs();

    afisare();
    return 0;
}