TTTTTTTTTTTTTT POJ 3678 与或异或 2-SAT+强连通 模板题
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
有一个有向图G(V,E),每条边e(a,b)上有一个位运算符op(AND, OR或XOR)和一个值c(0或1)。
问能不能在这个图上的每个点分配一个值X(0或1),使得每一条边e(a,b)满足 Xa op Xb = c
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#include <set>
using namespace std;
typedef long long ll;
typedef unsigned long long Ull;
#define MM(a,b) memset(a,b,sizeof(a));
const double eps = 1e-10;
const int inf =0x7f7f7f7f;
const double pi=acos(-1);
const int maxn=10+1000;
int n,m,pre[maxn],lowlink[maxn],dfs_clock,sccno[maxn],scc_cnt;
vector<int> G[2*maxn];
stack<int> S;
void read()
{
int a,b,c;char s[10];
scanf("%d %d %d %s",&a,&b,&c,s);
if(s[0]=='A')
{
if(c)
{
G[a].push_back(a+n);
G[b].push_back(b+n);
}
else
{
G[a+n].push_back(b);
G[b+n].push_back(a);
}
}
else if(s[0]=='O')
{
if(!c)
{
G[a+n].push_back(a);
G[b+n].push_back(b);
}
else
{
G[a].push_back(b+n);
G[b].push_back(a+n);
}
}
else if(s[0]=='X')
{
if(c)
{
G[a].push_back(b+n);
G[a+n].push_back(b);
G[b].push_back(a+n);
G[b+n].push_back(a);
}
else
{
G[a].push_back(b);
G[a+n].push_back(b+n);
G[b].push_back(a);
G[b+n].push_back(a+n);
}
}
}
void tarjan(int u)
{
pre[u]=lowlink[u]=++dfs_clock;
S.push(u);
for(int i=0;i<G[u].size();i++)
{
int v=G[u][i];
if(!pre[v])
{
tarjan(v);
lowlink[u]=min(lowlink[u],lowlink[v]);
}
else if(!sccno[v])
lowlink[u]=min(lowlink[u],pre[v]);
}
if(lowlink[u]==pre[u])
{
scc_cnt++;
while(1)
{
int x=S.top();S.pop();
sccno[x]=scc_cnt;
if(x==u) break;//找到了当前强连通的起始节点就退出,<br>//不然会破坏其他强连通分量
}
}
}
void find_scc()
{
MM(pre,0);
MM(sccno,0);
scc_cnt=dfs_clock=0;
for(int i=0;i<n;i++)
if(!pre[i])
tarjan(i);
}
int main()
{
while(~scanf("%d %d",&n,&m))
{
for(int i=0;i<2*n;i++) G[i].clear();
for(int i=1;i<=m;i++)
read();
find_scc();
int flag=1;
for(int i=0;i<n;i++)
if(sccno[i]==sccno[i+n])
{
flag=0;
break;
}
if(flag) printf("YES\n");
else printf("NO\n");
}
return 0;
}
2-sat的建图参考;
http://blog.csdn.net/u011466175/article/details/23048459?utm_source=tuicool&utm_medium=referral
和http://blog.csdn.net/leolin_/article/details/7215871