Cod sursa(job #3257674)

Utilizator Gabriel_DaescuDaescu Gabriel Florin Gabriel_Daescu Data 18 noiembrie 2024 20:46:58
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <fstream>
#include <vector>
#define NMAX 100002
using namespace std;
ifstream  fin("dfs.in");
ofstream fout("dfs.out");
int N,M,nr,viz[NMAX];
vector <int> v[NMAX];

void citire()
{
    int X,Y;
    fin>>N>>M;

    for(int i=1; i<=M; i++)
    {
        fin>>X>>Y;
        v[X].push_back(Y);
        v[Y].push_back(X);
    }
}

void DFS(int nod)
{
    int node,stiva[NMAX],h;
    h=1;
    stiva[h]=nod;

    while(h>0)
    {
        node=stiva[h];
        viz[node]=1;
        h--;

        for(int i=0; i<v[node].size(); i++)
        {
            if(!viz[v[node][i]])
            {
                stiva[++h]=v[node][i];
            }
        }
    }
}

int main()
{
    citire();

    nr=0;
    for(int i=1; i<=N; i++)
    {
        if(!viz[i])
        {
            nr++;
            DFS(i);
        }
    }

    fout<< nr << "\n";

    return 0;
}