Cod sursa(job #632236)

Utilizator Viva12Ferentz Sergiu Viva12 Data 10 noiembrie 2011 17:21:11
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <cstdio>
#define N 200000
using namespace std;
int n,m;
int x,y;
struct nod
{
    int inf;
    nod *urm;
}*l[2*N];
int viz[N];
void add(int x,nod *&p)
{
    nod *q=new nod;
    q->inf=x;
    q->urm=p;
    p=q;
}
void read()
{
    scanf("%d %d", &n,&m);
        for(int i=1;i<=m;i++)
        {
            scanf("%d %d",&x,&y);

            {add(x,l[y]);
            add(y,l[x]);
            }
        }
}

void dfs1(int vf)
{
    for(nod *i=l[vf];i;i=i->urm)
        {   if(!viz[i->inf])
            {
            viz[i->inf]=1;
            dfs1(i->inf);
            }
        }
}
void dfs()
{   int nr=0;
    for(int i=1;i<=n;i++)
        {
            if(!viz[i])
                {viz[i]=1;
                nr++;
                dfs1(i);

                }

        }
    printf("%d",nr);
}
int main()
{
    freopen("dfs.in","r",stdin);
    freopen("dfs.out","w",stdout);
    read();
    dfs();
    return 0;
}