您的位置:首页 > 其它

poj3678 Katu Puzzle 【解法二】

2016-08-04 14:08 281 查看
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”.

解法一见【这里】

和解法一有两个不同点。

一是处理确定的点时,比如a=1,连边a=0->a=1,这样a=0就一定会推出矛盾。

二是判断时求出强连通分量,然后看有没有某两个点a=0,a=1在同一个分量里。

#include<cstdio>
#include<cstring>
#include<vector>
#include<stack>
using namespace std;
vector<int> to[2010];
stack<int> sta;
int m,n,dfn[2010],low[2010],clo,tot,bel[2010];
bool in[2010];
void init()
{
int i,j,k,x,y,z;
char s[5];
scanf("%d%d",&n,&m);
for (i=1;i<=m;i++)
{
scanf("%d%d%d%s",&x,&y,&z,s+1);
if (s[1]=='A')
{
if (z==1)
{
to[2*x+1].push_back(2*x);
to[2*y+1].push_back(2*y);
}
else
{
to[2*x].push_back(2*y+1);
to[2*y].push_back(2*x+1);
}
}
if (s[1]=='O')
{
if (z==0)
{
to[2*x].push_back(2*x+1);
to[2*y].push_back(2*y+1);
}
else
{
to[2*x+1].push_back(2*y);
to[2*y+1].push_back(2*x);
}
}
if (s[1]=='X')
{
if (z==1)
{
to[2*x].push_back(2*y+1);
to[2*x+1].push_back(2*y);
to[2*y].push_back(2*x+1);
to[2*y+1].push_back(2*x);
}
else
{
to[2*x+1].push_back(2*y+1);
to[2*x].push_back(2*y);
to[2*y+1].push_back(2*x+1);
to[2*y].push_back(2*x);
}
}
}
}
void dfs(int x)
{
int i,j,k,p,q,u,v;
dfn[x]=low[x]=++clo;
sta.push(x);
in[x]=1;
for (i=0;i<to[x].size();i++)
{
u=to[x][i];
if (!dfn[u])
{
dfs(u);
low[x]=min(low[x],low[u]);
}
else if (in[u])
low[x]=min(low[x],dfn[u]);
}
if (low[x]==dfn[x])
{
tot++;
while (1)
{
p=sta.top();
sta.pop();
bel[p]=tot;
in[p]=0;
if (p==x) break;
}
}
}
void tarjan()
{
for (int i=0;i<2*n;i++)
if (!dfn[i]) dfs(i);
}
bool check()
{
for (int i=0;i<n;i++)
if (bel[2*i]==bel[2*i+1]) return 0;
return 1;
}
int main()
{
init();
tarjan();
if (check()) printf("YES\n");
else printf("NO\n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息