Cod sursa(job #1304526)

Utilizator whoasdas dasdas who Data 28 decembrie 2014 23:18:49
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.65 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;


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


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 n, 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, n);
		b = int2node(y, n);

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

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

	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, n)]) {
			dfs(G, seen, topo_stack, neg(i, n));
		}
	}

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

	/* for every node, remember what scc it is part of */
	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, n)] == scc) {
				printf("-1");
				return 0;
			}
		}
	}

	/*
	 * Traversing the sccs in topo order, we start with an scc with no incoming edges (parents).
	 * By assigning 0 to it we don't impose any restriction on its children.
	 * The symmetric scc won't have any outgoing edges (children) and assigning 1 to it doesn't
	 * impose any restriction on its parents.
	 * This way we eliminate the current scc pair without any impact on the rest of the graph.
	 * We can just proceed recursively.
	 */
	vector<int> scc2res(sccs.size(), -1);
	for (int scc = 0; scc < sccs.size(); scc++) {
		if (scc2res[scc] == -1) {
			int sym_scc = node2scc[neg(sccs[scc].front(), n)];
			scc2res[scc] = 0;
			scc2res[sym_scc] = 1;
		}
	}

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

	return 0;
}