Cod sursa(job #2256167)

Utilizator HerddexJinga Tudor Herddex Data 8 octombrie 2018 09:21:34
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");

struct Node
{
    int node;
    Node *next;
} *G[100001];

int N;

bool eVizitat[100001];

void dfs(int i)
{
    eVizitat[i] = true;
    for(Node *p = G[i]; p!=0; p = p->next)
        if(!eVizitat[p->node])
            dfs(p->node);
}

int main()
{
    int N, M;
    fin >> N >> M;
    while(M)
    {
        int x, y;
        fin >> x >> y;
        Node *p = new Node;
        p->node = y;
        p->next = G[x];
        G[x] = p;

        p = new Node;
        p->node = x;
        p->next = G[y];
        G[y] = p;

        M--;
    }

    int nrConexe = 0;
    for(int i=1; i<=N; i++)
        if(!eVizitat[i])
        {
            nrConexe++;
            dfs(i);
        }

    fout << nrConexe;

    fin.close();
    fout.close();
    return 0;
}