Cod sursa(job #796252)

Utilizator ciprianfFarcasanu Alexandru Ciprian ciprianf Data 10 octombrie 2012 21:28:17
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;
#define N_MAX 200010
#define FOR(i, v) for(vector<int>::iterator i = v.begin(); i != v.end(); i++)
vector<int> G[N_MAX];
queue<int> q;
int n,m ;
bool viz[N_MAX], sol[N_MAX];
void get_real(int &x) {
	if(x < 0) {
		x = (-x)+n;
	}
}
int get_other(int x) {
	if(x > n) {
		return x-n;
	}
	return x+n;
}

//df se apeleaza pt variabilele care iau val 0
bool df(int x) {
	
	sol[x] = 0;
	sol[get_other(x)] = 1;
	viz[x] = viz[get_other(x)] = 1;
	q.push(x);
	FOR(i, G[x]) {
		if(!viz[*i]) {
			int x = df(get_other(*i));
			if(x == 0) {
				return 0;
			}
		}
		else if(sol[*i] == 0) {
			return 0;
		}
	}
	return 1;
}

bool valid(int x, bool val) {
	
	if(val == true) { 
		return df(get_other(x));
	}
	else 
		return df(x);
}

void empty_queue() {
	while(!q.empty()) {
		q.pop();
	}
}
void reset_affected_nodes() {
	while(!q.empty()) {
		int x = q.front();
		q.pop();
		viz[x] = viz[get_other(x)] = 0;
	}
}
int main() {
	freopen("2sat.in", "r", stdin);
	freopen("2sat.out", "w", stdout);
	
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= m; i++) {
		int x, y;
		scanf("%d%d", &x, &y);
		get_real(x);
		get_real(y);
		G[x].push_back(y);
		G[y].push_back(x);
	}
	
	for(int i = 1; i <= n; i++) {
		if(viz[i]) {
			continue;
		}
		if(!valid(i, 0)) {
			reset_affected_nodes();
			if(!valid(i, 1)) {
				printf("-1\n");
				return 0;
			}
			empty_queue();
		}
	}
	
	for(int i = 1; i <= n; i++) {
		printf("%d ", sol[i]);
	}
	printf("\n");
	
	return 0;
}