Cod sursa(job #821310)

Utilizator ahmed.abdraboahmed.abdrabo ahmed.abdrabo Data 22 noiembrie 2012 04:20:46
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <algorithm>
#include <cstdio>
#include <vector>

using namespace std;

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

const int MAX = 200001;

int N, M;
bool seen1[MAX], seen2[MAX];
int X[MAX], Y[MAX], scc[MAX];
vector<int> order;
vector<int> G1[MAX], G2[MAX];

inline void add_edge_G(int x, int y) {
	x = x < 0 ? N - x : x;
	y = y < 0 ? N - y : y;
	G1[x].push_back(y);
	G2[y].push_back(x);
}

void dfs1(int u) {
	seen1[u] = true;
	for (size_t i = 0; i < G1[u].size(); i++) {
		if (!seen1[G1[u][i]]) {
			dfs1(G1[u][i]);
		}
	}
	order.push_back(u);
}

void dfs2(int u, int k) {
	seen2[u] = true;
	for (size_t i = 0; i < G2[u].size(); i++) {
		if (!seen2[G2[u][i]]) {
			dfs2(G2[u][i], k);
		}
	}
	scc[u] = k;
}

int main() {
	freopen("2sat.in", "r", stdin);
	freopen("2sat.out", "w", stdout);
	N = next_int();
	M = next_int();
	for (int i = 0; i < M; i++) {
		X[i] = next_int();
		Y[i] = next_int();
		add_edge_G(-X[i], Y[i]);
		add_edge_G(-Y[i], X[i]);
	}
	for (int i = 1; i <= N + N; i++) {
		if (!seen1[i]) {
			dfs1(i);
		}
	}
	for (int i = order.size() - 1, k = 0; i >= 0; i--) {
		if (!seen2[order[i]]) {
			dfs2(order[i], k++);
		}
	}
	for (int i = 1; i <= N; ++i) {
		if (scc[i] == scc[i + N]) {
			printf("-1");
			return 0;
		}
	}
	for (int i = 1; i <= N; ++i) {
		printf("%d ", scc[i] > scc[i + N]);
	}
	return 0;
}