Cod sursa(job #2796142)

Utilizator ScobiolaRaduScobiola Radu ScobiolaRadu Data 7 noiembrie 2021 17:29:13
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream in("bfs.in");
ofstream out("bfs.out");

const int maxi=100001;

class Graf
{
private:
    int n,m,s;
    vector<int> v[maxi];

public:
    Graf(bool tip);
    void bfs();
};

Graf::Graf(bool tip)
{
    int i;
    in>>n>>m>>s;
    for(i=1; i<=m; i++)
    {
        int x,y;
        in>>x>>y;
        v[x].push_back(y);
        if(tip==false)//e neorientat
            v[y].push_back(x);
    }
}

void Graf::bfs()
{
    int i;
    int dist[n+1];
    for(i=1; i<=n; i++)
        dist[i]=-1;
    dist[s]=0;
    queue<int> q;
    q.push(s);
    while(!q.empty())
    {
        int nc=q.front();//nod curent
        for(i=0; i<v[nc].size(); i++)
        {
            if(dist[v[nc][i]]==-1)
            {
                q.push(v[nc][i]);
                dist[v[nc][i]]=dist[nc]+1;
            }
        }
        q.pop();
    }
    for(i=1;i<=n;i++)
        out<<dist[i]<<" ";
    out.close();
}

int main()
{
    Graf g(true);
    g.bfs();
    return 0;
}