Cod sursa(job #1849832)

Utilizator TataruTataru Mihai Tataru Data 17 ianuarie 2017 21:05:22
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>

using namespace std;

const int NMAX = 1000001;
ifstream fin("bfs.in");
ofstream fout("bfs.out");

struct NOD
{
    int len, been;
};

int N, M, S;
vector<int> muc[NMAX];
NOD nod[NMAX];

void BFS()
{
    int crt;
    queue<int> Q;
    Q.push(S);
    nod[S].len = 0;
    nod[S].been = 1;
    while(!Q.empty())
    {
        crt = Q.back();
        Q.pop();
        for(int i = 0; i < muc[crt].size(); i++)
        {
            if(!nod[muc[crt][i]].been)
            {
                nod[muc[crt][i]].len = nod[crt].len + 1;
                nod[muc[crt][i]].been = 1;
                Q.push(muc[crt][i]);
            }
        }
    }
}

int main()
{
    fin >> N >> M >> S;
    int x, y;
    for(int i = 1; i <= N; ++i)
        nod[i].len = - 1;
    for(int i = 1; i <= M; i++)
    {
        fin >> x >> y;
        muc[x].push_back(y);
    }
    BFS();
    for(int i = 1; i <= N; ++i)
        fout << nod[i].len << ' ';
    return 0;
}