Cod sursa(job #2783722)

Utilizator oporanu.alexAlex Oporanu oporanu.alex Data 14 octombrie 2021 22:22:18
Problema BFS - Parcurgere in latime Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.56 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;

    Graph(int _noduri, int _muchii): noduri(_noduri), muchii(_muchii){
        /*for(int i = 0; i < _noduri + 1; ++i)
            {   vector <int> temp;
                adj.push_back(temp);
            }
        */
        for(int i = 0; i < 1005; ++i)
            dist[i] = -1;
    }

    /*int get_size(){
        return adj.size();
    }*/

    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 dfs(int nod){

        //cout << nod << " ";

        vis[nod] = true;
        for(unsigned i = 0; i < adj[nod].size(); ++i)
            if(!(vis[adj[nod][i]]))
                dfs(adj[nod][i]);
    }
*/

   /* long long getCconexe(){
        long long cnt = 0;
        for(int i = 1; i <= noduri; ++i)
            if(!(vis[i]))
            {
                ++cnt;
                dfs(i);
            }

        return cnt;
    }
    */

    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 << dist[i] << " ";
    return 0;

}