Cod sursa(job #812091)

Utilizator ahmed.abdraboahmed.abdrabo ahmed.abdrabo Data 13 noiembrie 2012 14:22:55
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <stack>
#include <vector>

using namespace std;

inline int next_int() {int d;scanf("%d", &d);return d;}

const int V = 1 << 17;
const int E = 1 << 18;

int ec, eb[V], en[E], et[E];

int time, id[V], low[V];
stack<pair<int, int> > stk;
vector<vector<int> > bcc;

void dfs(int u, int p = 0) {
	id[u] = low[u] = time++;
	for (int e = eb[u]; e != -1; e = en[e]) {
		int v = et[e];
		if (v == p) {
			continue;
		} else if (id[v] == -1) {
			stk.push(make_pair(u, v));
			dfs(v, u);
			low[u] = min(low[u], low[v]);
			if (low[v] >= id[u]) {
				vector<int> c;
				int x, y;
				do {
					x = stk.top().first, y = stk.top().second;
					c.push_back(x), c.push_back(y);
					stk.pop();
				} while (x != u || y != v);
				sort(c.begin(), c.end());
				c.erase(unique(c.begin(), c.end()), c.end());
				bcc.push_back(c);
			}
		} else {
			low[u] = min(low[u], id[v]);
		}
	}
}

int main() {
	freopen("biconex.in", "r", stdin);
	freopen("biconex.out", "w", stdout);
	memset(eb, -1, sizeof eb);
	memset(id, -1, sizeof id);
	int n = next_int();
	int m = next_int();
	for (int i = 0; i < m; i++) {
		int u = next_int();
		int v = next_int();
		et[ec] = v;
		en[ec] = eb[u];
		eb[u] = ec++;
		et[ec] = u;
		en[ec] = eb[v];
		eb[v] = ec++;
	}
	for (int i = 1; i <= n; i++) {
		if (id[i] == -1) {
			dfs(i);
		}
	}
	printf("%d\n", int(bcc.size()));
	for (size_t i = 0; i < bcc.size(); i++) {
		for (size_t j = 0; j < bcc[i].size(); j++) {
			printf("%d ", bcc[i][j]);
		}
		printf("\n");
	}
	return 0;
}