2-SAT算法学习笔记

2-SAT：

#include<bits/stdc++.h>

#define REP(i,a,b) for(int i=a;i<=b;++i)
typedef long long ll;

using namespace std;

void File(){
freopen("luogu4782.in","r",stdin);
freopen("luogu4782.out","w",stdout);
}

template<typename T>void read(T &_){
T __=0,mul=1; char ch=getchar();
while(!isdigit(ch)){
if(mul=='-')mul=-1;
ch=getchar();
}
while(isdigit(ch))__=(__<<1)+(__<<3)+(ch^'0'),ch=getchar();
_=__*mul;
}

const int maxn=1e6+10;
int n,m;
int beg[maxn<<1],to[maxn<<1],las[maxn<<1],cnte=1;
int bel[maxn<<1],cnt_scc,low[maxn<<1],dfn[maxn<<1],cnt_dfn;
stack<int>stk;

void add(int u,int v){las[++cnte]=beg[u];beg[u]=cnte;to[cnte]=v;}

void tarjan(int u){
low[u]=dfn[u]=++cnt_dfn;
stk.push(u);
for(int i=beg[u];i;i=las[i]){
if(!dfn[to[i]]){
tarjan(to[i]);
low[u]=min(low[u],low[to[i]]);
}
else if(!bel[to[i]])low[u]=min(low[u],dfn[to[i]]);
}
if(dfn[u]==low[u]){
++cnt_scc;
for(int p;p!=u;stk.pop()){
p=stk.top();
bel[p]=cnt_scc;
}
}
}

void init(){
int x,y,t1,t2;
REP(i,1,m){
}
}

void work(){
REP(i,1,(n<<1))if(!dfn[i])
tarjan(i);
REP(i,1,n)if(bel[i]==bel[i+n]){
puts("IMPOSSIBLE");
return;
}
puts("POSSIBLE");
REP(i,1,n){
if(bel[i]<bel[i+n])putchar('0');
else putchar('1');
putchar(' ');
}
}

int main(){
File();
init();
work();
return 0;
}