这道题目的建图很经典。
XOR的条件不同意出错。
但是OR和AND很容易忘记几个条件
//a :0 a+n:1
当运算符是OR的时候 c为0的情况 a 和 b不能是1 这两个条件容易漏掉 ,这个时候应该改加上条件 <a+n,a> <b+n,b>;
同理当运算符号是OR的时候 c为1的情况下a 和 b不能是0 同样两个条件 <a,a+n> <b,b+n>;很好理解,大家仔细想想就可以明白了;
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 6327 | Accepted: 2298 |
Description
Katu Puzzle is presented as a directed graph G(V, E) with each edgee(a, b) labeled by a boolean operatorop (one of AND, OR, XOR) and an integerc (0 ≤ c ≤ 1). One Katu is solvable if one can find each vertexVi a valueXi (0 ≤Xi≤ 1) such that for each edgee(a, b) labeled byop 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
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
using namespace std;
#define MAXN 10000
struct node
{
int to,next;
};
node edge[9000010],edge2[9000010];
int head[MAXN],en,dag[MAXN],en2,n,m;
void add(int a,int b)
{
edge[en].to=b;
edge[en].next=head[a];
head[a]=en++;
}
void add2(int a,int b)
{
edge2[en2].to=b;
edge2[en2].next=dag[a];
dag[a]=en2++;
}
int low[MAXN],dfn[MAXN];
int stack[MAXN],top,set[MAXN],col,num;
bool vis[MAXN],instack[MAXN];
void tarjan(int u)
{
vis[u]=1;
dfn[u]=low[u]=++num;
instack[u]=true;
stack[++top]=u;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
if(!vis[v])
{
tarjan(v);
low[u]=min(low[u],low[v]);
}
else
if(instack[v])
low[u]=min(dfn[v],low[u]);
}
if (dfn[u]==low[u])
{
int j;
col++;
do
{
j=stack[top--];
instack[j]=false;
set[j]=col;
}
while (j!=u);
}
}
void solve()
{
int i;
top=col=num=0;
memset(instack,0,sizeof(instack));
memset(vis,0,sizeof(vis));
memset(set,-1,sizeof(set));
for (i=0;i<2*n;i++)
if (!vis[i])
tarjan(i);
}
bool twosat()
{
solve();
for(int i=0;i<n;i++)
if(set[i]==set[i+n]) return false;
return true;
}
//i 0 i+n 1
int main()
{
int a,b,c;
char op[20];
while(~scanf("%d%d",&n,&m))
{
memset(head,-1,sizeof(head)),en=0;
for(int i=0;i<m;i++)
{
scanf("%d%d%d%s",&a,&b,&c,op);
if(strcmp(op,"AND")==0)
{
if(c==0)
{
add(a+n,b);
add(b+n,a);
}
else
{
add(a+n,b+n);
add(b+n,a+n);
add(a,a+n);
add(b,b+n);
}
}
if(strcmp(op,"OR")==0)
{
if(c==0)
{
add(a,b);
add(b,a);
add(a+n,a);
add(b+n,b);
}
else
{
add(a,b+n);
add(b,a+n);
}
}
if(strcmp(op,"XOR")==0)
{
if(c==0)
{
add(a,b);
add(a+n,b+n);
add(b,a);
add(b+n,a+n);
}
else
{
add(a,b+n);
add(a+n,b);
add(b,a+n);
add(b+n,a);
}
}
}
if(twosat())
{
printf("YES\n");
}
else
printf("NO\n");
}
return 0;
}