Cod sursa(job #520640)

Utilizator ciprianfFarcasanu Alexandru Ciprian ciprianf Data 9 ianuarie 2011 20:27:15
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 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, q2;
int SOL[NMAX], viz[NMAX];
int V[NMAX];
int n, m;
int OK;
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 relax(int x){
	FOR(i, G[x])
		if(!viz[*i]){
			SOL[*i] = 1;
			viz[*i] = viz[other(*i)] = 1;
			q2.push(*i);
			q.push(*i);
		}
		else if(SOL[*i] == 0) OK = 1;
}
void sterge(int x){
	SOL[x] = SOL[other(x)] = viz[x] = viz[other(x)] = 0;
}
int check(int y, int val){
	while(!q.empty()) q.pop();
	SOL[y] = val;
	OK = 0;
	q2.push(y);
	q.push(y);
	while(!q.empty()){
		if(OK) return 0;
		int x = q.front();
		q.pop();
		if(x <= n && SOL[x]) x += n;
		if(x > n && SOL[x]) x -= n;
		relax(x);
	}
	return 1;
}
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);
		G[real(x)].push_back(real(y));
		G[real(y)].push_back(real(x));
	}
	for(int i = 1; i <= n; ++i)
		V[i] = i;
	random_shuffle(V+1, V + n +1);
	for(int i = 1; i <= n; ++i)
		if(!viz[V[i]]) {
			//memcpy(SOL2, SOL, sizeof(SOL));
			//memcpy(viz2,viz, sizeof(viz));
			if(!check(V[i], 1)){
				while(!q2.empty()) sterge(q2.front()), q2.pop();
				//memcpy(SOL, SOL2, sizeof(SOL));
				//memcpy(viz,viz2, sizeof(viz));
				if(!check(V[i], 0)){
					printf("-1\n");
					return 0;
				}
			}
			while(!q2.empty()) q2.pop();
		}
	for(int i = 1; i <= n; ++i)
		printf("%d ", SOL[i]);
	return 0;
}