Cod sursa(job #2657439)

Utilizator tudorbuhniaTudor Buhnia tudorbuhnia Data 10 octombrie 2020 16:11:58
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
vector<int> v[100005];
queue<int> q;
bool vs[100005];
int vr[100005];
void edge(int x,int y)
{
    v[x].push_back(y);
    //v[y].push_back(x);
}
void bfs(int n)
{
    int x,k;
    q.push(n);
    while(q.empty()==false)
    {
        x=q.front();
        while(v[x].empty()==false)
        {
            k=v[x].back();
            v[x].pop_back();
            if(vs[k]==0)
            {
                vs[k]=1;
                q.push(k);
                vr[k]=vr[x]+1;
            }
        }
        q.pop();
    }
}
int main()
{
    ifstream cin("bfs.in");
    ofstream cout("bfs.out");
    int n,m,s,x,y;
    cin >> n >> m >> s;
    fill_n (vr+1, n, -1);
    for(int i=0;i<m;i++)
    {
        cin >> x >> y;
        if(x!=y)
            edge(x,y);
    }
    vs[s]=1;
    vr[s]=0;
    bfs(s);
    for(int i=1;i<=n;i++)
    {
        if(vs[i]==0)
            cout << -1 << " ";
        else
        {
            cout << vr[i] << " ";
        }
    }
    return 0;
}