2-SAT
入坑2-SAT qwq
2-SAT经典题,但因为求最小字典序,所以只能暴力判断。(要有信仰 O(nm) 是过得去的)
代码:
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 16001
#define M 40001
using namespace std;
struct edge{
int next,to;
}ed[M];
int n,m,k,h[N],stk[N],tp;
bool f[N];
inline char readc(){
static char buf[100000],*l=buf,*r=buf;
if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
if (l==r) return EOF; return *l++;
}
inline int _read(){
int x=0; char ch=readc();
if (ch==EOF) return -1;
while (!isdigit(ch)) ch=readc();
while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
return x;
}
inline void addedge(int x,int y){
ed[++k].next=h[x],ed[k].to=y,h[x]=k;
}
bool dfs(int x){//如果选了这个节点就必须选择其他节点
if (f[x]) return true; if (f[x^1]) return false;
f[x]=true,stk[++tp]=x;
for (int i=h[x];i;i=ed[i].next)
if (!dfs(ed[i].to)) return false;
return true;
}
inline bool t_sat(){
memset(f,false,sizeof(f));
for (int i=0;i<(n<<1);i+=2)
if (!f[i]&&!f[i^1]){//只有当两个都没有被选时才需要判断
tp=0; if (dfs(i)) continue;
while (tp) f[stk[tp--]]=false;
if (!dfs(i^1)) return false;
//如果另一个既选了又没选就是矛盾了
}
return true;
}
int main(){
while (~(n=_read())){
m=_read(),k=0;
memset(h,0,sizeof(h));
while (m--){
int x=_read()-1,y=_read()-1;
addedge(x,y^1),addedge(y,x^1);//建x->y的边表示选了x就必须选y
}
if (!t_sat()) { printf("NIE\n"); continue; }
for (int i=0;i<(n<<1);i++) if (f[i]) printf("%d\n",i+1);
}
return 0;
}