Cod sursa(job #1170406)

Utilizator harababurelPuscas Sergiu harababurel Data 13 aprilie 2014 15:26:29
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <set>
#include <algorithm>
#define nmax 100005
#define mmax 200005
using namespace std;

vector <int> v[nmax], comp[nmax];
stack <pair <int, int> > S;
set <int> V;
int n, m, a, b, comps = 0;
int depth[nmax], low[nmax], padre[nmax];
bool seen[nmax];

void buildComp(pair <int, int> E) {
	V.clear();
	bool cont = true;
	while(cont) {
		if(S.top() == E) cont = false;
		V.insert(S.top().first);
		V.insert(S.top().second);
		S.pop();
	}

	++comps;
	for(set<int>::iterator i=V.begin(); i!=V.end(); i++)
		comp[comps].push_back(*i);
}

void dfs(int x) {
	seen[x] = true;
	low[x] = depth[x];

	for(vector<int>::iterator y=v[x].begin(); y!=v[x].end(); y++) {
		if(seen[*y] && *y != padre[x]) low[x] = min(low[x], depth[*y]); //sigur ii o muchie de intoarcere
		if(!seen[*y]) {
			S.push(make_pair(x, *y));

			padre[*y] = x;
			depth[*y] = depth[x] + 1;
			dfs(*y);

			low[x] = min(low[x], low[*y]);

			if(low[*y] >= depth[x]) buildComp(make_pair(x, *y));
		}
	}

}

int main() {
	ifstream f("biconex.in");
	ofstream g("biconex.out");

	f>>n>>m;
	for(int i=1; i<=m; i++) {
		f>>a>>b;
		v[a].push_back(b);
		v[b].push_back(a);
	}

	dfs(1);

	g<<comps<<"\n";
	for(int i=1; i<=comps; i++) {
		for(vector<int>::iterator x=comp[i].begin(); x!=comp[i].end(); x++ ) g<<*x<<" ";
		g<<"\n";
	}


	return 0;
}