Cod sursa(job #213627)

Utilizator RobybrasovRobert Hangu Robybrasov Data 10 octombrie 2008 17:54:11
Problema Parcurgere DFS - componente conexe Scor 85
Compilator cpp Status done
Runda Arhiva educationala Marime 1.01 kb
#include <stdio.h>
#include <queue>

using namespace std;

typedef struct noduri
{
    int val;
    noduri *urm;
} adr;

adr *L[100000],*p;
short int E[100000];
int n,m,i,j,k,kont;
queue<int> c;

void bf(int nod)
{
    c.push(nod);
    E[nod]=1;
    while (!c.empty())
    {
        p=L[c.front()];
        while (p)
        {
            if (!E[p->val])
            {
                c.push(p->val);
                E[p->val]=1;
            }
            p=p->urm;
        }
        c.pop();
    }
}

int main()
{
    freopen("dfs.in","r",stdin);
    freopen("dfs.out","w",stdout);
    scanf("%d %d\n",&n,&m);
    for (k=1; k<=m; k++)
    {
        scanf("%d %d\n",&i,&j);
        p=new adr;
        p->val=j; p->urm=L[i];
        L[i]=p;
        p=new adr;
        p->val=i; p->urm=L[j];
        L[j]=p;
    }
    kont=0;
    for (i=1; i<=n; i++)
        if (!E[i])
        {
            kont++;
            bf(i);
        }
    printf("%d ",kont);

    return 0;
}