Cod sursa(job #209973)

Utilizator mircea_infoSuciu Mircea-Gabriel mircea_info Data 25 septembrie 2008 21:21:10
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <cstdio>
#include <stack>
#define max 100002

using namespace std;

int v,x,y,nr,n,numara;
int viz[max];

struct nod
{
    int nr;
    nod*urm;
};

nod *g[max];
stack <int> s;

void baga(int x, int y)
{
    nod *q=new nod;
    q->nr=y;
    q->urm=g[x];
    g[x]=q;
}

void read()
{
    freopen("dfs.in","r",stdin);
    v=1;
    scanf("%d%d",&n,&nr);
    for(int i=0;i<nr;i++)
    {
        scanf("%d%d",&x,&y);
        baga(x,y);
        baga(y,x);
    }
}

void adauga(int v2)
{
    nod *x=g[v2];
    while(x)
    {
        if(viz[x->nr]==0)
        {
            s.push(x->nr);
            viz[x->nr]=1;
        }
        x=x->urm;
    }
}

void dfs(int v)
{
    viz[v]=1;
    s.push(v);
    while(!s.empty())
    {
        int v2=s.top();
        s.pop();
        adauga(v2);
    }
}

int main()
{
    read();
    freopen("dfs.out","w",stdout);
    for(int i=1;i<=n;i++)
        if(viz[i]==0)
        {
            numara++;
            dfs(i);
        }
    printf("%d\n",numara);
    fclose(stdout);
    return 0;
}