Cod sursa(job #1304242)

Utilizator whoasdas dasdas who Data 28 decembrie 2014 19:42:11
Problema 2SAT Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.61 kb
#define IA_PROB "ctc"

#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>

#include <algorithm>

using namespace std;

typedef int node;
typedef stack<node, vector<node> > node_stack;
typedef list<node> adj_list;
typedef vector<adj_list> graph;


void dfs(graph &G, vector<bool> &seen, node_stack &stack, node x)
{
	assert(!seen[x]);
	seen[x] = true;
	for (adj_list::iterator i = G[x].begin(); i != G[x].end(); i++) {
		if (!seen[*i]) {
			dfs(G, seen, stack, *i);
		}
	}
	stack.push(x);
}

int main()
{
	freopen(IA_PROB".in", "r", stdin);
	freopen(IA_PROB".out", "w", stdout);

	int n, m;
	scanf("%d %d", &n, &m);

	vector<bool> seen(n + 1);
	graph G(n + 1);
	node_stack topo_stack;

	for (int i = 0; i < m; i++) {
		int x, y;
		scanf("%d %d", &x, &y);
		G[x].push_back(y);
	}

	for (int i = 1; i <= n; i++) {
		if (!seen[i]) {
			dfs(G, seen, topo_stack, i);
		}
	}

	/* reset seen */
	fill(seen.begin(), seen.end(), false);
	/* reverse graph*/
	graph Gr(n + 1);
	for (node i = 1; i <= n; i++) {
		for (adj_list::iterator j = G[i].begin(); j != G[i].end(); j++) {
			Gr[*j].push_back(i);
		}
	}
	/* release old G */
	G.clear();

	vector<node_stack> sccs;
	while(!topo_stack.empty()) {
		node node = topo_stack.top();
		topo_stack.pop();
		if (!seen[node]) {
			sccs.push_back(node_stack());
			dfs(Gr, seen, sccs.back(), node);
		}
	}

	printf("%d\n", sccs.size());
	for (vector<node_stack>::iterator i = sccs.begin(); i != sccs.end(); i++) {
		while (!i->empty()) {
			printf("%d ", i->top());
			i->pop();
		}
		printf("\n");
	}

	return 0;
}