Cod sursa(job #209884)

Utilizator dragosmihaiDragos Oana dragosmihai Data 25 septembrie 2008 11:37:41
Problema Parcurgere DFS - componente conexe Scor 65
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <fstream>
#include <stack>
using namespace std;

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

nod *gf[100000];
long nrcnx,n,m;
int viz[100000];
stack<long> s;

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

void citire()
{
    nrcnx=0;
    int x,y;
    ifstream f("dfs.in");
    f>>n>>m;
    for(int i=0;i<m;i++)
    {
        f>>x>>y;
        adaug(x,y);
        adaug(y,x);
    }
}

int vizitare()
{
    for(int i=1;i<=n;i++)
        if(!viz[i])
           return i;
    return 0;
}

void dfs()
{
    int xy=vizitare();
    while(xy){
    s.push(xy);
    viz[xy]=1;
    while(!s.empty())
    {
        int vf=s.top();
        //cout<<vf<<" ";
        s.pop();
        for(nod *o=gf[vf];o;o=o->urm)
            if(!viz[o->nr])
            {
                viz[o->nr]=1;
                s.push(o->nr);
            }
    }
    nrcnx++;
    xy=vizitare();
    }
}

void scriere()
{
    ofstream g("dfs.out");
    g<<nrcnx;
    g.close();
}

int main()
{
    citire();
    dfs();
    scriere();
    return 0;
}