和上一篇差不多,代码稍多
迷一样的数据,边数只开3W都能A?
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define ms(i) memset(i,0,sizeof(i))
const int N = 2005, M = 30000;
struct TwoSAT {
int h[N], p[M], v[M], vis[N], stk[N], top, cnt, n;
void add(int a, int x, int b, int y) {
a = 2 * a + x; b = 2 * b + y;
p[++cnt] = h[a ^ 1]; v[cnt] = b; h[a ^ 1] = cnt;
p[++cnt] = h[b ^ 1]; v[cnt] = a; h[b ^ 1] = cnt;
}
void init(int a) {
cnt = 0; n = a; ms(vis); ms(h);
}
bool solve() {
for(int i=0;i<2*n;i+=2) if (!vis[i]&&!vis[i^1]) {
top = 0;
if (!dfs(i)) {
while (top) vis[stk[--top]] = 0;
if (!dfs(i + 1)) return 0;
}
}
return 1;
}
bool dfs(int x) {
if (vis[x ^ 1]) return 0;
if (vis[x]) return 1;
vis[x] = 1; stk[top++] = x;
for (int i = h[x]; i; i = p[i])
if (!dfs(v[i])) return 0;
return 1;
}
} g;
int main() {
int n, m, a, b, c;
char d[4];
while (scanf("%d%d", &n, &m) == 2) {
g.init(n);
while (m--) {
scanf("%d%d%d%s", &a, &b, &c, d);
if (d[0] == 'A')
if (c) {
g.add(a, 0, b, 0);
g.add(a, 0, b, 1);
g.add(a, 1, b, 0);
} else
g.add(a, 1, b, 1);
else if (d[0] == 'O')
if (c)
g.add(a, 0, b, 0);
else {
g.add(a, 0, b, 1);
g.add(a, 1, b, 1);
g.add(a, 1, b, 1);
}
else if (d[0] == 'X')
if (c) {
g.add(a, 0, b, 0);
g.add(a, 1, b, 1);
} else {
g.add(a, 0, b, 1);
g.add(a, 1, b, 0);
}
}
puts(g.solve() ? "YES" : "NO");
}
return 0;
}
Katu Puzzle
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 9028 Accepted: 3346
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”.
Sample Input
4 4
0 1 1 AND
1 2 1 OR
3 2 0 AND
3 0 0 XOR
Sample Output
YES
Hint
X0 = 1, X1 = 1, X2 = 0, X3 = 1.