Cod sursa(job #900949)

Utilizator anonymous_l3510nAnonymous Romania anonymous_l3510n Data 28 februarie 2013 22:59:19
Problema Parcurgere DFS - componente conexe Scor 45
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <stack>
#include <vector>
#include <fstream>
#include <algorithm>

using namespace std;

const int Max = 32001;
int noNodes, noEdges, nextNode, countConexity, Mark[Max];
bool Adj[Max][Max];
stack<int> st;
vector<int> v;


void readData (fstream &in){
	int _nodeA, _nodeB;
	in >> noNodes >> noEdges;
	for (int i = 1; i <= noEdges; ++i){
		in >> _nodeA >> _nodeB;
		Adj[_nodeA][_nodeB] = Adj[_nodeB][_nodeA] = true;
	}
	in.close();
}

void depthFirstSearch (){
	st.push(nextNode);
	while (!st.empty()){
		int t = st.top();
		for (int i = noNodes; i >= 0; --i){
			if (Adj[t][i] && find(v.begin(), v.end(), i) == v.end()){
				st.push(i);
			}
		}
		if (find(v.begin(), v.end(), t) == v.end()){
			v.push_back(t);
			Mark[t] = countConexity;
		}
		else{
			st.pop();
		}
	}
}

void gotoNextNode(){
	for (int i = 1; i <= noNodes; ++i){
		if (!Mark[i]){
			nextNode = i;
			return;
		}
		else if (i == noNodes && Mark[i]){
			nextNode = 0;
			return;
		}
	}
}

void findConexityComponents (fstream &out){
	nextNode = 1;
	countConexity = 1;
	while (nextNode){
		while (!st.empty()){
			st.pop();
		}
		v.clear();
		depthFirstSearch();
		countConexity++;
		gotoNextNode();
	}
	out << --countConexity;
}

int main (int argc, char *argv[]){
	fstream in("dfs.in", ios::in);
	fstream out("dfs.out", ios::out);
	readData(in);
	findConexityComponents(out);
	return 0;
}