Pagini recente » Cod sursa (job #3136934) | Cod sursa (job #1176928) | Cod sursa (job #3219525) | Cod sursa (job #579684) | Cod sursa (job #797663)
Cod sursa(job #797663)
#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); A[b].pb(a);
}
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;
}