Cod sursa(job #2604747)

Utilizator GRalyGoia Raluca GRaly Data 23 aprilie 2020 13:52:36
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <fstream>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int t[2][1000005],start[100005],cost[100005];
short int ap[100005];
queue <int>co;
int main()
{
    int n,m,s,o,k=0,i,j;
    fin>>n>>m>>s;
    for(o=1;o<=m;o++)
    {
        k++;
        fin>>i>>j;
        t[0][k]=j;
        t[1][k]=start[i];
        start[i]=k;
    }
    co.push(s);
    ap[s]=1;
    cost[s]=0;
    while(!co.empty())
    {
        int nr=co.front();
        co.pop();
        k=start[nr];
        while(t[0][k]!=0)
            if(ap[t[0][k]]==0)
                {
                    ap[t[0][k]]=1;
                    co.push(t[0][k]);
                    cost[t[0][k]]=cost[nr]+1;
                    k=t[1][k];
                }
            else
                k=t[1][k];
    }
    for(i=1;i<=n;i++)
        if(cost[i]==0&&i!=s)
            fout<<-1<<' ';
        else
        fout<<cost[i]<<' ';
    return 0;
}