Cod sursa(job #557402)

Utilizator jupanubv92Popescu Marius jupanubv92 Data 16 martie 2011 17:23:04
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include<cstdio>
#define Nmx 1000001

using namespace std;

int n,m,viz[Nmx];
struct nod
{
    int inf;
    nod *urm;
};
nod *G[Nmx];

void add(int x,int y)
{
    nod *aux=new nod;
    aux->inf = y;
    aux->urm = G[x];
    G[x]=aux;
}


void citire()
{
    int x,y;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;++i)
    {
        scanf("%d%d",&x,&y);
        add(x,y);
        add(y,x);
    }
}

void dfs(int x)
{
    viz[x]=1;
    for(nod *p=G[x];p;p=p->urm)
        if(!viz[p->inf])
            dfs(p->inf);
}

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