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
//
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int maxn=2100000;
int V,E;//点数(1) 边数
struct edge//邻接表
{
int t,w;//u->t=w;
int next;
};
int p[maxn];//表头节点
edge G[maxn];
int l;
void init()
{
memset(p,-1,sizeof(p));
l=0;
}
//添加边
void addedge(int u,int t,int w)//u->t=w;
{
G[l].w=w;
G[l].t=t;
G[l].next=p[u];
p[u]=l++;
}
//tarjan算法 求有向图强联通分量
int dfn[maxn],lowc[maxn];
//dfn[u]节点u搜索的次序编号,lowc[u]u或者u的子树能够追溯到的栈中的最早的节点
int belg[maxn];//第i个节点属于belg[i]个强连通分量
int stck[maxn],stop;//stck栈
int instck[maxn];//第i个节点是否在栈中
int scnt;//强联通分量
int index;
void dfs(int i)
{
dfn[i]=lowc[i]=++index;
instck[i]=1;//节点i入栈
stck[++stop]=i;
for(int j=p[i];j!=-1;j=G[j].next)
{
int t=G[j].t;
//更新lowc数组
if(!dfn[t])//t没有遍历过
{
dfs(t);
if(lowc[i]>lowc[t]) lowc[i]=lowc[t];
}//t是i的祖先节点
else if(instck[t]&&lowc[i]>dfn[t]) lowc[i]=dfn[t];
}
//是强连通分量的根节点
if(dfn[i]==lowc[i])
{
scnt++;
int t;
do
{
t=stck[stop--];
instck[t]=0;
belg[t]=scnt;
}while(t!=i);
}
}
int tarjan()
{
stop=scnt=index=0;
memset(dfn,0,sizeof(dfn));
memset(instck,0,sizeof(instck));
for(int i=1;i<=V;i++)
{
if(!dfn[i]) dfs(i);
}
return scnt;
}
int main()
{
int n;
while(scanf("%d%d",&n,&E)==2)
{
V=2*n;//1 <=n 0 <=2*n
init();
for(int i=0;i<E;i++)
{
int u,v,s;
char str[10];
scanf("%d%d%d%s",&u,&v,&s,str);u++,v++;
if(str[0]=='A')
{
if(s==1)
{
addedge(u,v,1);
addedge(v,u,1);
addedge(u+n,u,1);//u,v必选
addedge(v+n,v,1);
}
else
{
addedge(u,v+n,1);
addedge(v,u+n,1);
}
}
else if(str[0]=='O')
{
if(s==0)
{
addedge(u+n,v+n,1);
addedge(v+n,u+n,1);
addedge(u,u+n,1);// !u,!v必选
addedge(v,v+n,1);
}
else
{
addedge(u+n,v,1);
addedge(v+n,u,1);
}
}
else
{
if(s==0)
{
addedge(u+n,v+n,1);
addedge(v+n,u+n,1);
addedge(u,v,1);
addedge(v,u,1);
}
else
{
addedge(u,v+n,1);
addedge(v,u+n,1);
addedge(u+n,v,1);
addedge(v+n,u,1);
}
}
}
tarjan();
int flag=1;
for(int i=1;i<=n;i++)
{
if(belg[i]==belg[i+n])
{
flag=0;break;
}
}
if(flag) printf("YES\n");
else printf("NO\n");
}
return 0;
}