Cod sursa(job #209889)

Utilizator dragosmihaiDragos Oana dragosmihai Data 25 septembrie 2008 12:00:18
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>
#include <queue>
using namespace std;

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

nod *gf[100002];
long n,m,xy,zz,nrcnx;
int viz[100002];
queue<long> q;

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

void citire()
{
    long 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);
    }
}

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

void bfs()
{
    nrcnx=0;
    zz=1;
    xy=vizitare(zz);
    while(xy){
    q.push(xy);
    viz[xy]=1;
    while(!q.empty())
    {
        long vf=q.front();

        q.pop();
        for(nod *o=gf[vf];o;o=o->urm)
            if(!viz[o->nr])
            {
                viz[o->nr]=1;
                q.push(o->nr);
            }
    }
    nrcnx++;
    xy=vizitare(zz);
    }
}

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

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