Cod sursa(job #1304491)

Utilizator whoasdas dasdas who Data 28 decembrie 2014 22:48:35
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 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 vector<node_list> graph;

int n;
node neg(node x) {
	return (x + n) % (2 * n);
}
node int2node(int x) {
	return x > 0 ? x : neg(-x);
}

void dfs(graph &G, vector<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 m;
	scanf("%d %d", &n, &m);

	graph G(2 * n, node_list()), Gr(2 * n, node_list());

	for (int i = 0; i < m; i++) {
		int x, y;
		scanf("%d %d", &x, &y);

		node a, b;
		a = int2node(x);
		b = int2node(y);

		G[neg(a)].push_back(b);
		G[neg(b)].push_back(a);

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

	node_list topo_stack;

	vector<bool> seen(2 * n, false);
	for (int i = 1; i <= n; i++) {
		if (!seen[i]) {
			dfs(G, seen, topo_stack, i);
		}
		if (!seen[neg(i)]) {
			dfs(G, seen, topo_stack, neg(i));
		}
	}

	fill(seen.begin(), seen.end(), 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);
		}
	}

	vector<int> node2scc(2 * n, -1);
	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[neg(*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[neg(sccs[scc].front())]] = 1;
		}
	}

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

	return 0;
}