Cod sursa(job #798311)

Utilizator tsubyRazvan Idomir tsuby Data 16 octombrie 2012 11:13:45
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.77 kb
#include <cstdio>

#define N 100001
using namespace std;

int n,m,viz[N],nr;

struct nod
{
    int x;
    nod *urm;
}*l[N];

void adaugare(int x, nod*&p)
{
    nod *q=new nod;
    q->x=x;
    q->urm=p;
    p=q;
}

void citire()
{
    int x,y;
    scanf("%d %d",&n,&m);
    for(int i=0;i<m;i++)
    {
        scanf("%d %d",&x,&y);
        adaugare(x,l[y]);
        adaugare(y,l[x]);
    }
}

void adancime(int v)
{
    viz[v]=1;
    for(nod *i=l[v];i;i=i->urm)
        if(!viz[i->x])
            adancime(i->x);
}

void conexe()
{
    for(int i=1;i<=n;i++)
        if(!viz[i])
        {
            nr++;
            adancime(i);
        }
}

int main()
{
    freopen("dfs.in","r",stdin);
    freopen("dfs.out","w",stdout);
    citire();
    conexe();
    printf("%d",nr);
    return 0;
}