Cod sursa(job #2783731)

Utilizator oporanu.alexAlex Oporanu oporanu.alex Data 14 octombrie 2021 22:35:39
Problema BFS - Parcurgere in latime Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#include <cstring>
#include <algorithm>

using namespace std;

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

    vector<int> adj[100005];
    queue<int>  q;
    ///bool vis[100005];
    int dist[100005];


class Graph{

public:

    int noduri, muchii;

    vector<int> adj[100005];
    queue<int>  q;
    ///bool vis[100005];

    int dist[100005];

    Graph(int _noduri, int _muchii): noduri(_noduri), muchii(_muchii){
        for(int i = 0; i < 100005; ++i)
            dist[i] = -1;
    }

    void build(){
        for(int i = 0; i < muchii; ++i)
        {
            int x, y;
            in >> x >> y;
            adj[x].push_back(y);
        }
    }

    void print(){
        for(int i = 1; i < noduri + 1; ++i)
        {   cout << i << ": ";
            for(unsigned j = 0; j < adj[i].size(); ++j)
                cout << adj[i][j] << " ";
            cout << "\n";
        }

    }

    void bfs(int source){

        //vis[source] = true;
        q.push(source);
        dist[source] = 0;

        while(!q.empty())
        {
            ///cout << q.front() << " ";
            int crt = q.front();
            ///vis[crt] = 1;
            q.pop();
            for(int i = 0; i < adj[crt].size(); ++i)
                {
                    if(dist[adj[crt][i]] == -1)
                        {
                            dist[adj[crt][i]] = 1 + dist[crt];
                            q.push(adj[crt][i]);
                            //vis[adj[crt][i]] = true;
                        }

                }


        }
    }

    void sol(){
        for(int i = 0; i < noduri; ++i)
                cout << dist[i] << " ";
    }
};

int main()
{
    int N, M, S;
    in >> N >> M;
    Graph g(N, M);
    in >> S;

    g.build();

    g.print();

    g.bfs(S);

    for(int i = 1; i <= g.noduri; ++i)
        out << g.dist[i] << " ";
    return 0;

}