Cod sursa(job #1304459)

Utilizator whoasdas dasdas who Data 28 decembrie 2014 22:24:22
Problema 2SAT Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
#define IA_PROB "2sat"

#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 list<node> node_list;
typedef map<node, node_list> graph;

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

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

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

	graph G, Gr;
	map<node, bool> seen;

	for (node i = 1; i <= n; i++) {
		G[i] = node_list();
		G[-i] = node_list();

		Gr[i] = node_list();
		Gr[-i] = node_list();

		seen[i] = false;
		seen[-i] = false;
	}

	for (int i = 0; i < m; i++) {
		int a, b;
		scanf("%d %d", &a, &b); //  a or b

		G[-a].push_back(b); 	// !a -> b
		G[-b].push_back(a); 	// !b -> a

		Gr[a].push_back(-b);
		Gr[b].push_back(-a);
	}

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

	/* reset seen */
	for (int i = 1; i <= n; i++) {
		seen[i] = false;
		seen[-i] = false;
	}

	/* dfs on the reversed graph, starting from nodes in topological order */
	vector<node_list> sccs;
	while (!topo_stack.empty()) {
		node node = topo_stack.front();
		topo_stack.pop_front();
		if (!seen[node]) {
			sccs.push_back(node_list());
			dfs(Gr, seen, sccs.back(), node);
		}
	}

	map<node, int> node2scc;
	for (int scc = 0; scc < sccs.size(); scc++) {
		for (node_list::iterator x = sccs[scc].begin(); x != sccs[scc].end(); x++) {
			node2scc[*x] = scc;
			if (node2scc.count(-*x) && node2scc[-*x] == scc) {
				printf("-1\n");
				return 0;
			}
		}
	}

	vector<int> scc2res(sccs.size(), -1);
	for (int scc = 0; scc < sccs.size(); scc++) {
		if (scc2res[scc] == -1) {
			scc2res[scc] = 0;
			scc2res[node2scc[-sccs[scc].front()]] = 1;
		}
	}

	for (node i = 1; i <= n; i++) {
		printf("%d ", scc2res[node2scc[i]]);
	}

	return 0;
}