2-SAT problem study notes + example [Luo Gu P4792]

A nice 2-SAT article: Portal

Entering the problem

What is 2-SAT

SAT is short for Posedness (Satisfiability) problem. The general form for the adaptability of the k- abbreviated k-SAT.

First, the "2" and "SAT" apart. Satisfiability SAT is the acronym meaning satisfiability. That is a bunch of Boolean variables, each can only be true or false. These variables are required for the assignment to meet a Boolean equation.

How to achieve 2-SAT

An example: Luo Gu P4782 2-SAT examples

First convert each question or to fake -> real problem

Then ran shrink point

Because the condensing point topology ran out of sequence has been determined of strongly connected components (albeit in reverse) in the process, and then determines again

When the strongly connected components of the topology Sequence Topological sequence of strongly connected components in ¬x where x where x is taken as true it. During use of the compression algorithm Tarjan find points strongly connected component, it has been marked in good order for each strongly connected component , but is the opposite of topological order .

The Code

#include<bits/stdc++.h>
#define re register
#define ll long long
using namespace std;
inline int read()
{
    ll k=1,sum=0;
    char c=getchar();
    for(;c<'0' || c>'9';c=getchar()) if(c=='-') k=-1;
    for(;c>='0' && c<='9';c=getchar()) sum=sum*10+c-'0';
    return sum*k;
}
const int N=1e6+10;
int n,m;
struct Edge{
    int to,nxt;
};
int head[N<<1],cnt;
Edge edge[N<<2];
inline void Add(int x,int y){
    edge[++cnt].to=y;edge[cnt].nxt=head[x];head[x]=cnt;
}
int dfn[N<<1],ins[N<<1],color[N<<1],low[N<<1],col;
bool vis[N<<1];
int id;
stack<int> S;
inline void Tarjan(int x){
    S.push(x);
    ins[x]=1;
    dfn[x]=low[x]=++id;
    for(re int i=head[x];i;i=edge[i].nxt){
        int y=edge[i].to;
        if(!dfn[y]){
            Tarjan(y);
            low[x]=min(low[x],low[y]);
        }
        else if(ins[y]) low[x]=min(low[x],low[y]);
    }
    if(low[x]==dfn[x]) {
        re int k=-1;++col;
        while(k!=x){
            k=S.top();S.pop();
            ins[k]=0;
            color[k]=col;
        }
    }
}
int main()
{
    n=read();m=read();
    for(re int k=1;k<=m;++k){
        int i=read(),a=read(),j=read(),b=read();
        Add(i+n*(a&1),j+n*(b^1));
        Add(j+n*(b&1),i+n*(a^1));
    }
    for(re int i=1;i<=n<<1;++i){
        if(!dfn[i]) Tarjan(i);
    }
    for(re int i=1;i<=n;++i)
    if(color[i]==color[i+n]){
        puts("IMPOSSIBLE");
        return 0;
    }
    puts("POSSIBLE");
    for(re int i=1;i<=n;++i) {
        cout<<((color[i]<color[i+n])?1:0)<<" ";
    }
    return 0;
}

Guess you like

Origin www.cnblogs.com/IcedMoon/p/11432288.html