Cod sursa(job #465619)

Utilizator IrnukIrina Grosu Irnuk Data 24 iunie 2010 23:49:42
Problema Parcurgere DFS - componente conexe Scor 15
Compilator cpp Status done
Runda Arhiva educationala Marime 2.29 kb
#include <fstream>
#include <list>
#include <vector>
#include <stack>
#include <iostream>

#define NMAX 100005
using namespace std;

class Nod
{
public:
	Nod(long newVal)
	{
		val=newVal;
	}
	long getVal()
	{
		return val;
	}
	void setVal(long newVal)
	{
		val=newVal;
	}

private:
	long val;
	

};

class Graf
{
public:
	Graf(long newNrVarfuri, long newNrMuchii)
	{
		nrVarfuri = newNrVarfuri;
		nrMuchii = newNrMuchii;
	}
	vector<list<Nod*>*> D;
	list<Nod*> dfsList;
	long nrVarfuri;
	long nrMuchii;
	void dfs();
	void afiseaza();
	void afiseazaDfs();
	static long contor;
};

long Graf::contor=0;

void Graf::dfs()
{
	vector<int> S;
	vector<Nod*> p;
	int ok=1;
	for(long i = 0; i <= nrVarfuri; i++)
	{
		S.push_back(0);
		if(i!=0)
		p.push_back(*D[i]->begin());
	}
	stack<Nod*> SB;
	

	SB.push(*p.begin());
	S[1]=1;
	do
	{
		ok=0;
		contor++;
		while(!SB.empty())
		{
			Nod *nod = SB.top();
			SB.pop();
			dfsList.push_back(nod);

			list<Nod*>::iterator i;
			for(i = D[nod->getVal()]->begin(); i != D[nod->getVal()]->end(); i++)
			{
				if(S[(*i)->getVal()]==0)
				{
					SB.push(*i);
					S[(*i)->getVal()]=1;
				}
			}

		}
		for(int k=1; k <= this->nrVarfuri; k++)
			if(S[k]==0)
			{
				S[k]=1;
				SB.push(*D[k]->begin());
				ok=1;
				break;
			}

	}while(ok);

//	this->afiseazaDfs();


}

void Graf::afiseazaDfs()
{
	fstream fout;
	fout.open("dfs.out",ios::out);

	//list<Nod*>::iterator i;

	//for(i=dfsList.begin(); i != dfsList.end(); i++)
	//	fout<<(*i)->getVal()<<" ";

	fout<<contor<<'\n';
}

void Graf::afiseaza()
{
	for(long i = 1; i <= nrVarfuri; i++)
	{
		cout<<i<<'\t';
		if(!D[i]->empty())
		{
			list<Nod*>::iterator j;
			for(j=D[i]->begin(); j != D[i]->end(); j++)
			{
				cout<<(*j)->getVal()<<" ";
			}
		}
		cout<<'\n';
	}
}

int main()
{
	fstream fin;
	long n,m,x,y;
	
	fin.open("dfs.in",ios::in);

	fin>>n>>m;
	Graf grf(n,m);
//	list<Nod*> vida;
	
	for(long i = 0 ;i <= n+1; i++)
	{
		grf.D.push_back(new list<Nod*>);
		grf.D[i]->push_back(new Nod(i));
	}

	for(long i = 1; i <= m; i++)
	{
		fin>>x>>y;
		Nod *n = new Nod(y);
		grf.D[x]->push_back(n);

	}
	grf.dfs();
	//grf.afiseaza();
	grf.afiseazaDfs();
	
	//getchar();
	return 0;
}