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
X 0 = 1, X 1 = 1, X 2 = 0, X 3 = 1.
**思路:**判断是否有解问题,按照要求加边就行了。
代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#define maxn 2005
#define maxx 5000005
#define INF 0x3f3f3f3f
using namespace std;
int n,_n,m;
int head[maxn],to[maxx],_next[maxx],edge;
inline void addEdge(int x,int y)
{
to[++edge]=y,_next[edge]=head[x],head[x]=edge;
}
int dfn[maxn],low[maxn],_index=0;
int st[maxn],cnt=0;
bool inS[maxn];
int be[maxn],tot=0;
void tarjan(int u)
{
dfn[u]=low[u]=++_index;
st[++cnt]=u;inS[u]=true;
for(int i=head[u];i;i=_next[i])
{
int v=to[i];
if(!dfn[v])
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else if(inS[v])low[u]=min(low[u],dfn[v]);
}
if(dfn[u]==low[u])
{
++tot;int now;
do
{
now=st[cnt--];
inS[now]=false;
be[now]=tot;
}while(u!=now);
}
}
int main()
{
cin>>n>>m;
char s[10];
int x,y,z;
for(int i=0;i<m;i++)
{
scanf("%d%d%d%s",&x,&y,&z,s);
if(s[0]=='A')
{
if(z==1)
{
addEdge(x,x+n);
addEdge(y,y+n);
addEdge(x+n,y+n);
addEdge(y+n,x+n);
}
else
{
addEdge(x+n,y);
addEdge(y+n,x);
}
}
else
if(s[0]=='O')
{
if(z==0)
{
addEdge(x+n,x);
addEdge(y+n,y);
addEdge(x,y);
addEdge(y,x);
}
else
{
addEdge(x,y+n);
addEdge(y,x+n);
}
}
else
{
if(z==0)
{
addEdge(x,y);
addEdge(y,x);
addEdge(x+n,y+n);
addEdge(y+n,x+n);
}
else
{
addEdge(x,y+n);
addEdge(y+n,x);
addEdge(x+n,y);
addEdge(y,x+n);
}
}
}
for(int i=0;i<2*n;i++)
if(!dfn[i])tarjan(i);
bool sign=true;
for(int i=0;i<n;i++)
if(be[i]==be[i+n])
{
sign=false;
break;
}
if(sign)printf("YES\n");
else printf("NO\n");
return 0;
}