Cod sursa(job #2793221)

Utilizator Radu_FilipescuFilipescu Radu Radu_Filipescu Data 3 noiembrie 2021 12:15:21
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.54 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin( "dfs.in" );
ofstream fout( "dfs.out" );

class graph {
private:
    int N;                      /// number of nodes
    vector< vector<int> > ad;
    vector< vector<int> > cost;
    vector<int> dist;
    vector<int> aux;            /// auxiliary vector, for different needs
    int conexComponents;        /// requires DFSTraversal to set the value
    void Dfs( int node ) {
        aux.push_back( node );
        dist[node] = 1;

        for( int i = 0; i < ad[node].size(); ++i ) {
            int w = ad[node][i];

            if( dist[w] == 0 )
                Dfs( w );
        }
    }
public:
    graph( int n ) {
        N = n;
        ad.resize( n + 1 );
        cost.resize( n + 1 );
        dist.resize( n + 1 );
    }
    void changeN( int n ) {
        N = n;
        ad.resize( n + 1 );
        cost.resize( n + 1 );
        dist.resize( n + 1 );
    }
    int getN() { return N; }
    void addEdge( int x, int y, bool directed = false, int c = 0 ) {
        ad[x].push_back(y);
        cost[x].push_back(c);

        if( !directed ) {
            ad[y].push_back(x);
            cost[y].push_back(c);
        }
    }
    vector <int> DfsTraversal() {
        aux.clear();
        conexComponents = 0;

        for( int i = 1; i <= N; ++i )
            dist[i] = 0;

        for( int i = 1; i <= N; i++ )
            if( dist[i] == 0 ) {
                Dfs( i );
                ++conexComponents;
            }

        return aux;
    }
    void BfsTraversal( int source ) {
        queue<int> Q;

        for( int i = 0; i <= N; i++ )
            dist[i] = 0;

        dist[source] = 1;
        Q.push( source );

        while( !Q.empty() ) {
            int u = Q.front();
            Q.pop();

            for( int i = 0; i < ad[u].size(); ++i ) {
                int w = ad[u][i];

                if( dist[w] == 0 ) {
                    dist[w] = dist[u] + 1;
                    Q.push( w );
                }
            }
        }
    }

    int getConexComponents() {   /// requires DFS to be called first
        return conexComponents;
    }
};


int main()
{
    int n, m;
    fin >> n >> m;

    graph G(n);

    int x, y;
    for( int i = 1; i <= m; i++ ) {
        fin >> x >> y;
        G.addEdge( x, y, false );
    }

    vector <int> X = G.DfsTraversal();

    //for( int i = 0; i < X.size(); ++i )
    //    fout << X[i] << ' ';

    fout << G.getConexComponents();

    return 0;
}