## poj3678Katu Puzzle

2019年11月08日 算法 ⁄ 共 1935字 ⁄ 字号 评论关闭

```#include<iostream>
#include<map>
#include<string>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
const int MAXN = 1010;
struct twosat
{
int n,c;
vector<int> g[MAXN<<1];
bool mark[MAXN<<1];
int s[MAXN<<1];

bool dfs(int x)
{
int i;
if (mark[x^1])
return 0;
if (mark[x])
return 1;
mark[x] = 1;
s[c++] = x;
for (i = 0; i < g[x].size(); i++)
if (!dfs(g[x][i]))
return 0;
return 1;
}

void init(int n)
{
int i,t=n<<1;
this->n = n;
for (i = 0; i < t; i++)
g[i].clear();
memset(mark, 0, sizeof(mark));
}

void add_clause(int x,int xval,int y,int yval)
{
x=x*2+xval;
y=y*2+yval;
g[x].push_back(y^1);
g[y].push_back(x^1);
}

bool solve()
{
int i,t=n<<1;
for (i = 0; i < t; i += 2)
if (!mark[i] && !mark[i + 1])
{
c = 0;
if (!dfs(i))
{
while (c > 0)
mark[s[--c]] =0;
if (!dfs(i + 1))
return 0;
}
}
return 1;
}
}ender;
int work(int a,int b,int k)
{
return k==0?a&b:k==1?a|b:a^b;
}
int main()
{
char s[100];
int a,b,c,n,m,x,y,k;
while(cin>>n>>m)
{
ender.init(n);
while(m--)
{
scanf("%d%d%d%s",&a,&b,&c,s);
k=strcmp(s,"AND")==0?0:strcmp(s,"OR")==0?1:2;
for(x=0;x<2;x++)
for(y=0;y<2;y++)
if(work(x,y,k)!=c)
}
cout<<(ender.solve()?"YES":"NO")<<endl;

}
return 0;
}```

Katu Puzzle

 Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 8007 Accepted: 2943

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:

 AND 0 1 0 0 0 1 0 1
 OR 0 1 0 0 1 1 1 1
 XOR 0 1 0 0 1 1 1 0

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.

Source