Cod sursa(job #1469415)

Utilizator al.mocanuAlexandru Mocanu al.mocanu Data 8 august 2015 12:02:59
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <stdio.h>
#include <vector>
#define MAX 200005
using namespace std;

vector<int> G[MAX], Grev[MAX];
int n, m, i, x, y;
int sol[MAX], negsol, v[MAX];
bool onStack[MAX];

int negativ(int x){
	if(x <= n)
		return x + n;
	return x - n;
}

void DFS(int node);
void DFSrev(int node);

int main(){
	freopen("2sat.in", "r", stdin);
	freopen("2sat.out", "w", stdout);
	scanf("%d%d", &n, &m);
	for(i = 0; i < m; i++){
		scanf("%d%d", &x, &y);
		if(x < 0)
			x = n - x;
		if(y < 0)
			y = n - y;
		G[negativ(x)].push_back(y);
		G[negativ(y)].push_back(x);
		Grev[x].push_back(negativ(y));
		Grev[y].push_back(negativ(x));
	}

	for(i = 1; i <= 2 * n; i++)
		if(!onStack[i])
			DFS(i);

	for(i = 2 * n; i > 0; i--)
		if(onStack[v[i]] && onStack[negativ(v[i])])
			DFSrev(v[i]);

	if(negsol)
		printf("-1");
	else
		for(i = 1; i <= n; i++)
			printf("%d ", sol[i]);
	return 0;
}

void DFS(int node){
	onStack[node] = true;
	int i;
	for(i = 0; i < G[node].size(); i++)
		if(!onStack[G[node][i]])
			DFS(G[node][i]);
	v[++v[0]] = node;
}

void DFSrev(int node){
	if(sol[node])
		negsol = 1;
	sol[negativ(node)] = 1;
	onStack[node] = false;
	int i;
	for(i = 0; i < Grev[node].size(); i++)
		if(onStack[Grev[node][i]])
			DFSrev(Grev[node][i]);
}