POJ 3905
阅读原文时间:2023年07月14日阅读:1

加深了对有向边意义的理解了。2-SAT

#include
#include
#include
#include
#include
using namespace std;

const int MAXN=;
const int MAXM=;

int head[MAXN],dfn[MAXN],low[MAXN],st[MAXN],stop,belong[MAXN],tot,index,pat;
bool stack[MAXN];
struct {
int u,v;
int next;
}edge[MAXM];
int n,m;
int s1,s2;

void init(){
stop=; tot=; index=; pat=-;
for(int i=;i<*n;i++){
head[i]=-;
dfn[i]=low[i]=;
belong[i]=-;
stack[i]=false;
}
}

void addedge(int u,int v){
edge[tot].u=u;
edge[tot].v=v;
edge[tot].next=head[u];
head[u]=tot++;
}

void tarjan(int u){
int v;
dfn[u]=low[u]=++index;
st[stop++]=u; stack[u]=true;
for(int e=head[u];e!=-;e=edge[e].next){
v=edge[e].v;
if(dfn[v]==){
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(stack[v]){
low[u]=min(low[u],dfn[v]);
}
}
if(dfn[u]==low[u]){
pat++;
do{
v=st[--stop];
stack[v]=false;
belong[v]=pat;
}while(u!=v);
}
}

int main(){
int u,v;
while(scanf("%d%d",&n,&m)!=EOF){
init();
for(int i=;i<=m;i++){ scanf("%d%d",&s1,&s2); u=abs(s1)-; v=abs(s2)-; // cout<&&s2>){
addedge(*u,*v+);
addedge(*v,*u+);
}
else if(s1>&&s2<){ addedge(*u,*v); addedge(*v+,*u+); } else if(s1<&&s2>){
addedge(*u+,*v+);
addedge(*v,*u);
}
else{
addedge(*u+,*v);
addedge(*v+,*u);
}
}
for(int i=;i<*n;i++){
if(dfn[i]==)
tarjan(i);
}
bool flag=true;
for(int i=;i<n;i++){
if(belong[i*]==belong[i*+]){
printf("0\n");
flag=false;
break;
}
}
if(flag)
printf("1\n");
}
}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器