Cod sursa(job #1170401)

Utilizator harababurelPuscas Sergiu harababurel Data 13 aprilie 2014 15:21:40
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 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(int i=0; i<int(v[x].size()); i++) {
		if(seen[v[x][i]] && v[x][i] != padre[x]) low[x] = min(low[x], depth[v[x][i]]);
		if(!seen[v[x][i]]) {
			S.push(make_pair(x, v[x][i]));

			padre[v[x][i]] = x;
			depth[v[x][i]] = depth[x] + 1;
			dfs(v[x][i]);

			low[x] = min(low[x], low[v[x][i]]);

			if(low[v[x][i]] >= depth[x]) buildComp(make_pair(x, v[x][i]));
		}
	}

}

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);

	//for(int i=1; i<=n; i++) cout<<depth[i]<<" "; cout<<"\n";
	//for(int i=1; i<=n; i++) cout<<low[i]<<" "; cout<<"\n";

	g<<comps<<"\n";
	for(int i=1; i<=comps; i++) {
		for(int j=0; j<int(comp[i].size()); j++) g<<comp[i][j]<<" ";
		g<<"\n";
	}


	return 0;
}