传送门:POJ 3678
Problem Description
Katu Puzzle is presented as a directed graph G(V, E) with each edge e(a, b) labeled by a boolean operator op (one of AND, OR, XOR) and an integer c (0 ≤ c ≤ 1). One Katu is solvable if one can find each vertex Vi a value Xi (0 ≤ Xi ≤ 1) such that for each edge e(a, b) labeled by op and c, the following formula holds:
Xa op Xb = c
The calculating rules are:
Given a Katu Puzzle, your task is to determine whether it is solvable.
Input
The first line contains two integers N (1 ≤ N ≤ 1000) and M,(0 ≤ M ≤ 1,000,000) indicating the number of vertices and edges.
The following M lines contain three integers a (0 ≤ a < N), b(0 ≤ b < N), c and an operator op each, describing the edges.
Output
Output a line containing “YES” or “NO”.
Sample Input
4 4
0 1 1 AND
1 2 1 OR
3 2 0 AND
3 0 0 XOR
Sample Output
YES
Hint
X0 = 1, X1 = 1, X2 = 0, X3 = 1.
题意:
有n个Xi…告诉你m个位运算( AND OR XOR )结果…问是否有存在可行解
使得每个Xa op Xb = c都成立。
题解:
对于X里的每个数,我们都只可以取0和1两个数,m次的位运算就是限制条件,典型的2-SAT题。
记对于Xi的两个取值
a
a
a代表1,
a
′
a'
a′代表0
要注意的几个限制条件是:
- A AND B=1:A,B必须都是1,所以有 a ′ − > a , b ′ − > b a'->a,b'->b a′−>a,b′−>b;
- A OR B=0:A,B必须都是0,所以有 a − > a ′ , b − > b ′ a->a', b->b' a−>a′,b−>b′;
其他的按照运算规则建边即可。
AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<vector>
#define ll long long
using namespace std;
const int N=1100;
int n,m,top;
bool mark[2*N];
int stack[2*N];
vector<int> g[2*N];
int a,b,c;
char op[5];
void init()
{
memset(mark,false,sizeof(mark));
for(int i=0;i<2*N;i++)
{
g[i].clear();
}
}
void addedge(int x,int idx,int y,int idy)
{
x=2*x+idx;
y=2*y+idy;
g[x].push_back(y);
}
bool dfs(int x)
{
if(mark[x^1]) return false;
if(mark[x]) return true;
mark[x]=true;
stack[++top]=x;
int len=g[x].size();
for(int i=0;i<len;i++)
{
if(!dfs(g[x][i])) return false;
}
return true;
}
bool twosat()
{
for(int i=0;i<2*n;i+=2)
{
if(!mark[i]&&!mark[i+1])
{
top=0;
if(!dfs(i))
{
while(top>0)
mark[stack[top--]]=false;
if(!dfs(i+1)) return false;
}
}
}
return true;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
init();
for(int i=0;i<m;i++)
{
scanf("%d%d%d%s",&a,&b,&c,op);
if(op[0]=='A')
{
if(c==1)
{
addedge(a,0,a,1);
addedge(b,0,b,1);
}
else
{
addedge(a,1,b,0);
addedge(b,1,a,0);
}
}
if(op[0]=='O')
{
if(c==0)
{
addedge(a,1,a,0);
addedge(b,1,b,0);
}
else
{
addedge(a,0,b,1);
addedge(b,0,a,1);
}
}
if(op[0]=='X')
{
if(c==1)
{
addedge(a,0,b,1);
addedge(a,1,b,0);
addedge(b,0,a,1);
addedge(b,1,a,0);
}
else
{
addedge(a,0,b,0);
addedge(a,1,b,1);
addedge(b,0,a,0);
addedge(b,1,a,1);
}
}
}
if(twosat()) printf("YES\n");
else printf("NO\n");
}
return 0;
}