Cod sursa(job #1267576)

Utilizator raztaapDumitru raztaap Data 20 noiembrie 2014 00:38:41
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <cstdio>
struct nod{int nd; nod *next;};
nod *L[100100];
int ST[100100], n, m, nr, uz[100100], 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)
{
    nod *p;
    int k;
    ST[1]=val;
    uz[val]=1;
    k=1;
    while(k)
    {
        X=ST[k];
        p=L[X];
        while(p&&uz[p->nd])
            p=p->next;
        if(!p)
            --k;
        else
        {
            uz[p->nd]=1;
            ST[++k]=p->nd;
        }
    }
}
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;
}