Cod sursa(job #754542)

Utilizator random.personRandom Person random.person Data 2 iunie 2012 15:36:44
Problema 2SAT Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#define NMAX 200005
#define pb push_back
using namespace std;
int n,m,A[NMAX],r,sol[NMAX];
vector <int> G[NMAX],GT[NMAX];
char viz[NMAX];
inline int neg(int x)
{
	return x<=n ? x+n : x-n;
}
void read()
{
	scanf("%d%d",&n,&m);
	int i,x,y;
	for (i=1; i<=m; i++)
	{
		scanf("%d%d",&x,&y);
		if (x<0) x=-x+n;
		if (y<0) y=-y+n;
		G[neg(y)].pb(x);  GT[x].pb(neg(y)); 
		G[neg(x)].pb(y);  GT[y].pb(neg(x)); 
	}
}
void dfs(int nod)
{
	viz[nod]=1;
	int i,vec;
	for (i=0; i<G[nod].size(); i++)
	{
		vec=G[nod][i];
		if (!viz[vec])
			dfs(vec);
	}
	A[++r]=nod;
}
void dfs2(int nod)
{
	if (sol[nod])
	{
		printf("-1\n");
		exit(0);
	}
	viz[nod]=1;
	sol[nod]=0; sol[neg(nod)]=1;
	int i,vec;
	for (i=0; i<GT[nod].size(); i++)
	{
		vec=GT[nod][i];
		if (!viz[vec])
			dfs2(vec);
	}
}
void solve()
{
	int i;
	for (i=1; i<=2*n; i++)
		if (!viz[i])
			dfs(i);
	memset(viz,0,sizeof(viz));
	for (i=r; i>=1; i--)
		if (!viz[A[i]] && !viz[neg(A[i])])
			dfs2(A[i]);
	for (i=1; i<=n; i++)
		printf("%d ",sol[i]);
}
int main()
{
	freopen("2sat.in","r",stdin);
	freopen("2sat.out","w",stdout);
	read();
	solve();
	return 0;
}