Cod sursa(job #488113)

Utilizator AndrewTheGreatAndrei Alexandrescu AndrewTheGreat Data 27 septembrie 2010 18:13:28
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <iostream>
#include <stdio.h>
#define Max 100010

using namespace std;

int M, N;

struct nod{
    int info;
    nod *next;
};

nod *G[Max];

void add(int a, int b)
{
    nod *p = new nod;
    p->info = b;
    p->next = G[a];
    G[a] = p;
}

void citire()
{
    int a, b;
    scanf("%d %d",&N,&M);
    for(int i = 1; i <= M; i++)
    {
        scanf("%d %d",&a,&b);
        add(b,a);
        add(a,b);
    }
}

int viz[Max];

void DFS(int x)
{
    viz[x] = 1;
    nod *p = new nod;
    p = G[x];
    while(p)
    {
        if(!viz[p->info])
            DFS(p->info);
        p=p->next;
    }
}

int main()
{
    freopen ("dfs.in","r",stdin);
    freopen ("dfs.out","w",stdout);
    citire();
    int nr = 0;
    for(int i = 1; i <= N; i++)
        if(!viz[i])
        {
            nr++;
            DFS(i);
        }
    printf("%d\n",nr);
    return 0;
}