Cod sursa(job #2274406)

Utilizator vic_d54Doroftei Victor vic_d54 Data 1 noiembrie 2018 19:13:04
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#define NMAX 100000
using namespace std;
ifstream in("dfs.in");
ofstream out("dfs.out");
int n,m,nrc;
bool viz[NMAX+5];

vector <int> a[NMAX+5];
stack  <int> st;

void dfs(int nc)
{
    int i;
    st.push(nc);
    while(!st.empty())
    {
        nc=st.top();
        st.pop();
        if(!viz[nc])
        {
            //out<<nc<<' ';
            viz[nc]=1;
        }
        for(i=0;i<a[nc].size();i++)
            if(!viz[a[nc][i]])
                st.push(a[nc][i]);
    }
}
int main()
{
    int i,x,y;
    in>>n>>m;
    for(i=1;i<=m;i++)
    {
        in>>x>>y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    for(i=1;i<=n;i++)
        if(!viz[i])
        {
            nrc++;
            dfs(i);
        }
    out<<nrc;
    return 0;
}