Cod sursa(job #797660)

Utilizator radustn92Radu Stancu radustn92 Data 14 octombrie 2012 16:34:52
Problema 2SAT Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <stdio.h>
#include <vector>
#include <queue>
#define NMAX 200005
#define pb push_back
using namespace std;
int n,m;
vector <int> A[NMAX];
queue <int> Q,Q2;
bool val[NMAX],check[NMAX];
inline int get_other(int x)
{
	return x>n ? x-n : x+n; 
}
inline int dfs(int nod)
{
	Q.push(nod);
	int i,vec;
	for (i=0; i<A[nod].size(); i++)
	{
		vec=A[nod][i];
		if (check[vec] && !val[vec])
			return 0;
		if (!check[vec])
		{
			val[vec]=1; val[get_other(vec)]=0;
			check[vec]=1; check[get_other(vec)]=1;
			if (!dfs(get_other(vec)))
				return 0;
		}
	}
	return 1;
}
inline int valid(int nod,int value)
{
	val[nod]=value; val[get_other(nod)]=value ^ 1; 
	check[nod]=1; check[get_other(nod)]=1;
	if (value==0)
		return dfs(nod);
	return dfs(get_other(nod));
}
void reset_values()
{
	int nod;
	while (!Q.empty())
	{
		nod=Q.front();
		check[nod]=check[get_other(nod)]=0;
		Q.pop();
	}
}
int main()
{
	freopen("2sat.in","r",stdin);
	freopen("2sat.out","w",stdout);
	scanf("%d%d",&n,&m);
	int i,a,b;
	for (i=1; i<=m; i++)
	{
		scanf("%d%d",&a,&b);
		if (a<0) a=get_other(-a);
		if (b<0) b=get_other(-b);
		A[a].pb(b);
	}
	for (i=1; i<=n; i++)
		if (!check[i])
		{
			if (!valid(i,0))
			{
				reset_values();
				if (!valid(i,1))
				{
					printf("-1\n");
					return 0;
				}
				Q=Q2;
			}
		}
	for (i=1; i<=n; i++)
		printf("%d ",val[i]);
	printf("\n");
	return 0;
}