2-sat
Nt_Tsumiki · · 算法·理论
前言
你说的对,但是 2-sat 是一种解决二元关系的图论算法,中间忘了,后面忘了。
正文
2-sat 是用来解决类似于选了
一个简单的例子:
对于两个数
一个 2-sat 板子。
我们考虑吧每个数
那么对于某对矛盾关系,如果有
结束了吗?
没有。
我们知道对于
好了,我们现在图建完了,那问题来了,我么每个
分几种情况。
那具体到图上怎么体现呢。
缩点,然后拓扑。
我们定义
那么对于情况 3,体现在图中就是
关键在于情况 1,2 和 4,这就不能单纯的用
原因在于强连通分量的性质。
因为强连通分量的中的两个点
那么现在就有两种情况。
Code
#include <iostream>
#include <cstdio>
using namespace std;
int n,m,cnt,tot,top,sccnum;
int head[2000001],dfn[2000001],low[2000001],scc[2000001],s[2000001];
struct Node { int to,nxt; }e[2000001];
void add(int x,int y) { e[++cnt]=Node{y,head[x]},head[x]=cnt; }
void tarjan(int x) {
dfn[x]=low[x]=++tot,s[++top]=x;
for (int i=head[x];i;i=e[i].nxt) {
int y=e[i].to;
if (!dfn[y]) {
tarjan(y);
low[x]=min(low[x],low[y]);
} else if (!scc[y]) low[x]=min(low[x],dfn[y]);
}
if (dfn[x]==low[x]) {
++sccnum;
do scc[s[top]]=sccnum; while (s[top--]!=x);
}
}
int main() {
scanf("%d%d",&n,&m);
for (int i=1,x,a,y,b;i<=m;i++) {
scanf("%d%d%d%d",&x,&a,&y,&b);
add(x+a*n,y+(b^1)*n),add(y+b*n,x+(a^1)*n);
}
for (int i=1;i<=(n<<1);i++)
if (!dfn[i]) tarjan(i);
for (int i=1;i<=n;i++)
if (scc[i]==scc[i+n]) {
printf("IMPOSSIBLE\n");
return 0;
}
printf("POSSIBLE\n");
for (int i=1;i<=n;i++) printf("%d ",(int)scc[i]<scc[i+n]);
return 0;
}