Cod sursa(job #210091)

Utilizator RobytzzaIonescu Robert Marius Robytzza Data 26 septembrie 2008 15:46:54
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <fstream>
#include <fstream>
#include <queue>
#define max 100001

using namespace std;

ifstream fin ("dfs.in");
ofstream fout ("dfs.out");

int n,m;
int viz[max];

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

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

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

void citire()
{
    int x,y;
    fin>>n>>m;
    for(int i=0;i<m;i++)
    {
        fin>>x>>y;
        baga(x,y);
        baga(y,x);
    }
}

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

void BFS(int n)
{
    viz[n]=1;
    s.push(n);
    while(!s.empty())
    {
        int v=s.front();
        s.pop();
        adauga(v);
    }
}

int main()
{
    citire();
    int nr=0;
    for(int i=1;i<=n;i++)
        if(viz[i]==0)
        {
            nr++;
            BFS(i);
        }
    fout<<nr;
    fout.close();
    fin.close();
    return 0;

}