Cod sursa(job #2379792)

Utilizator AndrulianDin Iulian Andrulian Data 14 martie 2019 07:55:15
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
const int nmax=100005;
unsigned int n,m;
bool viz[nmax];
vector < int> nod[nmax];

int nr=0;
void DFS_iterativ(int x)
{
    //int st[nmax]= {0};
    stack<int>st;
    st.push(x);
    //viz[x]=1;
    while(!st.empty())
    {
        int el_din_varf=st.top();///iau elementul din varful stivei
        st.pop();///il si scot dupa ce l folosesc
        for(int i=0; i<nod[el_din_varf].size(); i++)
        {
            ///ii parcurg vecinii si ii marchez corespunzator
            int next=nod[el_din_varf][i];
            if(!viz[next])
            {
                viz[next]=1;
                st.push(next);
            }

        }
    }
}
void DFS(int x)
{
    viz[x]=1;
    for(int i=0; i<nod[x].size(); i++)
    {
        int next=nod[x][i];
        if(!viz[next])
            DFS(next);
    }
}
int main()
{

    fin>>n>>m;
    while(m--)
    {
        int x1=0,x2=0;
        fin>>x1>>x2;
        nod[x1].push_back(x2);
        nod[x2].push_back(x1);
    }

   /* for(int i=1; i<=n; i++)
    {
        cout<<"nodul  "<<i<<" are "<<nod[i].size()<<" vecini\n";
        for(int j=0; j<nod[i].size(); j++)
            cout<<nod[i][j]<<" ";
        cout<<endl;
    }*/

    for(int i=1; i<=n; i++)
    {
        if(!viz[i])
        {
            nr++;
            DFS_iterativ(i);
        }
    }
    fout<<nr;
}