题目描述:
给出n个布尔变量xi,每个变量或者取1或者取0,给出m条两个变量的逻辑运算结果,运算包括与或异或三种。问是否存在一种取值方法使得m条关系成立。
大致思路:
看题目描述很像2-SAT的定义,但是就是在过程中构造边的地方有点复杂,容易出错。具体过程看程序。
代码:
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;
const int maxn = 1010;
struct TwoSAT {
int n;
vector<int> G[maxn*2];
bool mark[maxn*2];
int S[maxn*2],c;
bool dfs(int x) {
if (mark[x^1]) return false;
if (mark[x]) return true;
mark[x] = true;
S[c++] = x;
for (int i = 0; i < G[x].size(); i++)
if (!dfs(G[x][i])) return false;
return true;
}
void init(int n) {
this->n = n;
for (int i = 0; i < n*2; i++) G[i].clear();
memset(mark,0,sizeof(mark));
}
void add_clause(int x,int xval,int y,int yval) {
x = x * 2 + xval;
y = y * 2 + yval;
G[x].push_back(y);
//G[y^1].push_back(x);
}
bool solve() {
for (int i = 0; i < n*2; i += 2)
if (!mark[i] && !mark[i+1]) {
c = 0;
if (!dfs(i)) {
while (c > 0) mark[S[--c]] = false;
if (!dfs(i+1)) return false;
}
}
return true;
}
};
int n,m;
int main() {
while (cin>>n>>m) {
TwoSAT ts;
ts.init(n);
for (int i = 0; i < m; i++) {
char s[10];
int a,b,c;
scanf("%d%d%d%s",&a,&b,&c,s);
if (s[0] == 'A' && c == 1) {
ts.add_clause(a,1,b,1);
ts.add_clause(b,1,a,1);
ts.add_clause(a,0,a,1);
ts.add_clause(b,0,b,1);
}
else if (s[0] == 'A' && c == 0) {
ts.add_clause(a,1,b,0);
ts.add_clause(b,1,a,0);
}
else if (s[0] == 'O' && c == 1) {
ts.add_clause(a,0,b,1);
ts.add_clause(b,0,a,1);
}
else if (s[0] == 'O' && c == 0) {
ts.add_clause(a,0,b,0);
ts.add_clause(b,0,a,0);
ts.add_clause(a,1,a,0);
ts.add_clause(b,1,b,0);
}
else if (s[0] == 'X' && c == 0) {
ts.add_clause(a,1,b,1);
ts.add_clause(a,0,b,0);
ts.add_clause(b,1,a,1);
ts.add_clause(b,0,a,0);
}
else if (s[0] == 'X' && c == 1) {
ts.add_clause(a,0,b,1);
ts.add_clause(a,1,b,0);
ts.add_clause(b,0,a,1);
ts.add_clause(b,1,a,0);
}
}
if (ts.solve()) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}