Cod sursa(job #520843)

Utilizator ciprianfFarcasanu Alexandru Ciprian ciprianf Data 10 ianuarie 2011 16:54:22
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include <stdio.h>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define FOR(i, v) for(vector<int>::iterator i = v.begin(); i != v.end(); ++i)
#define NMAX 200010
vector <int> G[NMAX];
queue <int> q;
int SOL[NMAX], viz[NMAX];
int n, m;
int VAL, not_sol;
inline int real(int x){
	if(x < 0) return n-x;
	return x;
}
inline int other(int x){
	if(x > n) return x-n;
	return x+n;
}
void df(int x){
	if(not_sol) return;
	FOR(i, G[x])
		if(!viz[*i]){
			SOL[*i] = 1;
			viz[*i] = viz[other(*i)] = 1;
			df(other(*i));
			q.push(*i);
		}
		else if(SOL[*i] == 0) {
			not_sol = 1;
			return;
		}
}

int check(int y, int val){
	VAL = val;
	SOL[y] = val;
	if(val == 1) y = other(y);
	not_sol = 0;
	df(y);
	if(not_sol) return 0;
	return 1;
}
void add(int x, int y){
	G[real(x)].push_back(real(y));
	G[real(y)].push_back(real(x));
}
void sterge(int x){
	SOL[x] = SOL[other(x)] = viz[x] = viz[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);
		add(x,y);
	}
	for(int i = 1; i <= n; ++i)
		if(!viz[i]) {
			if(!check(i, 1)){ //daca nu am solutie
				while(!q.empty()) sterge(q.front()), q.pop(); //anulez atribuirile facute in check(i,1)
				if(!check(i, 0)){
					printf("-1\n");
					return 0;
				}
			}
			while(!q.empty()) q.pop(); //am solutie(atribuiri satisfiabile) deci golesc doar coada
		}
	for(int i = 1; i <= n; ++i)
		printf("%d ", SOL[i]);
	return 0;
}