Cod sursa(job #2304072)

Utilizator valorosu_300Cristian Gherman valorosu_300 Data 17 decembrie 2018 14:54:35
Problema Parcurgere DFS - componente conexe Scor 15
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream in("dfs.in");
ofstream out("dfs.out");
const int MAX_SIZE = 100005;

vector <int> v[MAX_SIZE];
int st[MAX_SIZE]; ///stack
bool vis[MAX_SIZE]; ///visited nodes

void DFS(int n, int src){
    int h = 1; ///height of stack
    int top, sz; ///size
    int nbr; ///neighbor

    st[h] = src;
    vis[src] = true;

    while(h > 0){
        top = st[h--];
        sz = v[top].size();

        for(int i=0;i<sz;i++){
            nbr = v[top][i];
            if(vis[nbr] == false){
                vis[nbr] = true;
                st[++h] = nbr;
            }
        }

    }
}

int main()
{
    int n, m, x, y, nrConex = 0;

    in>>n>>m;
    for(int i=1;i<=m;i++){
        in>>x>>y;
        v[x].push_back(y);
    }
    in.close();

    for(int i=1;i<=n;i++)
        if(vis[i] == false){
            nrConex++;
            DFS(n,i);
        }

    out<<nrConex<<"\n";
    out.close();
    return 0;
}