poj 3678 2-SAT (Katu Puzzle)

题意:欲构建n个点m条边的图,限制为:定点只能取01二值之一。对每条边给出如下信息:连接的两个顶点、一种预算('&'、'|'、'^'三种之一)和一个值(0或1),要求两个顶点的取值进行对应运算得到给定值。问满足输入限制的图能否构建成功:

思路:2-SAT。对每个定点i,i表示取0,i+n表示取1;枚举三种运算和给定结果建图。

#include <stdio.h>
#include <string.h>
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define N 10010
struct edge{
	int y,next;
}e[8*1000010];
int n,m,component,top,tops,id;
int first[N],dfn[N],low[N],stack[N],strong[N];
void init(){
	tops = -1;
	top = component = id = 0;
	memset(first,-1,sizeof(first));
	memset(dfn,-1,sizeof(dfn));
	memset(strong,0,sizeof(strong));
}
void add(int x,int y){
	e[top].y = y;
	e[top].next = first[x];
	first[x] = top++;
}
void tarjan(int x){
	int i,y;
	dfn[x] = low[x] = ++id;
	stack[++tops] = x;
	for(i = first[x];i!=-1;i=e[i].next){
		y = e[i].y;
		if(dfn[y] == -1){
			tarjan(y);
			low[x] = min(low[x],low[y]);
		}
		else if(!strong[y])
			low[x] = min(low[x],dfn[y]);
	}
	if(dfn[x] == low[x]){
		component++;
		do{
			strong[stack[tops]] = component;
		}while(stack[tops--] != x);
	}
}
int main(){
	int i,j;
	freopen("a.txt","r",stdin);
	while(scanf("%d %d",&n,&m)!=EOF){
		int i,j,a,b,c;
		char s[5];
		init();
		for(i = 1;i<=m;i++){
			scanf("%d %d %d %s",&a,&b,&c,s);
			if(!strcmp(s,"AND")){
				if(c){
					add(a,b);add(a,b+n);
					add(b,a);add(b,a+n);
					add(a+n,b+n);add(b+n,a+n);
				}else{
					add(a+n,b);add(b+n,a);
				}
			}else if(!strcmp(s,"OR")){
				if(c){
					add(a,b+n);add(b,a+n);
				}else{
					add(a+n,b);add(a+n,b+n);
					add(b+n,a);add(b+n,a+n);
					add(a,b);add(b,a);
				}
			}else{
				if(c){
					add(a,b+n);add(a+n,b);
					add(b,a+n);add(b+n,a);
				}else{
					add(a,b);add(a+n,b+n);
					add(b,a);add(b+n,a+n);
				}
			}		
		}
		for(i = 0;i<2*n;i++)
			if(dfn[i] == -1)
				tarjan(i);
		for(i = 0;i<n;i++)
			if(strong[i] && (strong[i] == strong[i+n]))
				break;
		if(i>=n)
			printf("YES\n");
		else
			printf("NO\n");
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值