oneman233

P4782 【模板】2-SAT 问题(2-SAT)

就只是模板而已

代码:

#include <bits/stdc++.h>
//luogu P4782
using namespace std;
const int N=2e6+5;

int n,m,a,va,b,vb;
int dfn[N],low[N],timer=0;
stack<int> s;
bool vis[N];
vector<int> e[N];
int co[N],color=0;

void add(int x,int y)
{
	e[x].push_back(y);
}

void tarjan(int u)
{
	dfn[u]=low[u]=++timer;
	s.push(u);
	vis[u]=1;
	for(auto v:e[u])
	{
		if(!dfn[v])
			tarjan(v),
			low[u]=min(low[u],low[v]);
		else if(vis[v])
			low[u]=min(low[u],dfn[v]);
	}
	if(low[u]==dfn[u])
	{
		int v;
		color++;
		do
		{
			v=s.top();
			s.pop();
			vis[v]=0;
			co[v]=color;
		}
		while(u!=v);
	}
}

bool solve()
{
	for(int i=1;i<=2*n;++i)
		if(!dfn[i]) tarjan(i);
	for(int i=1;i<=n;++i)
		if(co[i]==co[i+n])
			return 0;
	return 1;
}

int main()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;++i)
	{
		scanf("%d%d%d%d",&a,&va,&b,&vb);
		int nota=va^1,notb=vb^1;
		add(a+nota*n,b+vb*n);//not a and b
		add(b+notb*n,a+va*n);//not b and a
	}
	if(solve())
	{
		puts("POSSIBLE");
		for(int i=1;i<=n;++i)
			printf("%d ",co[i]>co[i+n]);
	}
	else puts("IMPOSSIBLE");
	return 0;
}

posted on 2019-10-21 22:44  oneman233  阅读(120)  评论(0编辑  收藏  举报

导航