Cod sursa(job #1813148)

Utilizator andrei1299Ghiorghe Andrei Alexandru andrei1299 Data 22 noiembrie 2016 18:59:29
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>

using namespace std;
int s,n,m,sol[100003];
vector <int> a[100003];
queue <int> q;

void Citire()
{
    int x,y;
    ifstream fin("bfs.in");
    fin>>n>>m>>s;
    for(int i=1;i<=m;i++)
    {
        fin>>x>>y;
        if(x!=y)
            a[x].push_back(y);
    }
    fin.close();
}

void Afisare()
{
    ofstream fout("bfs.out");
    for(int i=1;i<=n;i++)
        fout<<sol[i]<<" ";
    fout.close();
}

void BFS()
{
    int i,x;
    unsigned k;
    for(i=1;i<=n;i++)
        sol[i]=-1;
    sol[s]=0;
    q.push(s);
    while(!q.empty())
    {
        x=q.front();
        q.pop();
        for(k=0;k<a[x].size();k++)
        {
            if(sol[a[x][k]]==-1)
            {
                q.push(a[x][k]);
                sol[a[x][k]]=sol[x]+1;
            }
        }

    }
}


int main()
{
    Citire();
    BFS();
    Afisare();
    return 0;
}