2-SAT问题可以通过强连通分量来判断条件是否矛盾。
而题目往往会要求输出方案,输出方案时,强连通分量的scc值,会和原图的拓扑序紧密联系在一起。
#include <bits/stdc++.h>
using namespace std;
const int N=1e6+5;
int n,m,a,b,nowa,nowb;
int cnt,head[N<<1];
int col,now,top,dfn[N<<1],low[N<<1],color[N<<1],sta[N<<1],si[N<<1];
bool jay;
struct edge{
int next,from,to;}e[N<<1];
inline void add(int u,int v)
{
cnt++;
e[cnt].next=head[u];
e[cnt].from=u;
e[cnt].to=v;
head[u]=cnt;
}
inline void tarjan(int u)
{
dfn[u]=low[u]=++now;
sta[++top]=u;
for (register int i=head[u]; i; i=e[i].next)
{
if (!dfn[e[i].to])
{
tarjan(e[i].to);
low[u]=min(low[u],low[e[i].to]);
}
else if (!color[e[i].to])
low[u]=min(low[u],dfn[e[i].to]);
}
if (low[u]==dfn[u])
{
color[u]=++col;
si[col]++;
while (sta[top]!=u) color[sta[top]]=col,si[col]++,top--;
top--;
}
}
int main(){
scanf("%d%d",&n,&m);
for (register int i=1; i<=m; ++i)
{
scanf("%d%d%d%d",&a,&nowa,&b,&nowb);
add(a+(nowa^1)*n,b+nowb*n);
add(b+(nowb^1)*n,a+nowa*n);
}
for (register int i=1; i<=2*n; ++i) if (!dfn[i]) tarjan(i);
jay=true;
for (register int i=1; i<=n; ++i) if (color[i]==color[i+n]) {
jay=false; break;}
if (!jay) puts("IMPOSSIBLE");
else
{
puts("POSSIBLE");
for (register int i=1; i<=n; ++i)
if (color[i+n]<color[i]) printf("%d ",1); else printf("%d ",0);
}
return 0;
}