Cod sursa(job #1380137)

Utilizator misu007Pogonaru Mihai misu007 Data 6 martie 2015 22:17:46
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.72 kb
#include <cstdio>
using namespace std;

int n,viz[100001];

struct nod
{
    int x;
    nod *u;
}*a[100001];

void dfs(int x)
{
    nod* nd=a[x];
    viz[x]=1;
    while(nd)
    {
        if(!viz[nd->x]) dfs(nd->x);
        nd=nd->u;
    }
}

int main()
{
    freopen("dfs.in","r",stdin);
    freopen("dfs.out","w",stdout);
    int m,x,y,nrcc=0;
    nod* nd;
    scanf("%d%d",&n,&m);
    while(m)
    {
        --m;
        scanf("%d%d",&x,&y);
        nd=new nod;
        nd->u=a[x];
        a[x]=nd;
        nd->x=y;
        nd=new nod;
        nd->u=a[y];
        a[y]=nd;
        nd->x=x;
    }
    for(x=1;x<=n;++x)if(!viz[x]){++nrcc;dfs(x);}
    printf("%d\n",nrcc);
    return 0;
}