Cod sursa(job #1556897)

Utilizator raztaapDumitru raztaap Data 26 decembrie 2015 12:15:48
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include <cstdio>
#define MAXN 100100
struct nod{int nd; nod *next;};
nod *L[MAXN];
int ST[MAXN], uz[MAXN], n, m, nr, X;
void citire()
{
    int i, x, y;
    nod *p;
    scanf("%d%d", &n, &m);
    for(i=1;i<=m;++i)
    {
        scanf("%d%d", &x, &y);
        p=new nod;
        p->nd=y;
        p->next=L[x];
        L[x]=p;
        p=new nod;
        p->nd=x;
        p->next=L[y];
        L[y]=p;
    }
}
void dfs(int val)
{
    int k;
    nod *p;
    k=1;
    ST[1]=val;
    uz[val]=1;
    while(k)
    {
        X=ST[k];
        p=L[X];
        while(p&&uz[p->nd])
            p=p->next;
        if(!p)
            --k;
        else
        {
            ST[++k]=p->nd;
            uz[p->nd]=1;
        }
    }
}
void rezolva_problema()
{
    int i;
    citire();
    for(i=1;i<=n;++i)
        if(!uz[i])
        {
            ++nr;
            dfs(i);
        }
    printf("%d\n", nr);
}
int main()
{
    freopen("dfs.in", "r", stdin);
    freopen("dfs.out", "w", stdout);
    rezolva_problema();
    return 0;
}