-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2SAT.cpp
More file actions
98 lines (87 loc) · 2.14 KB
/
2SAT.cpp
File metadata and controls
98 lines (87 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <bits/stdc++.h>
using namespace std;
struct TwoSat {
int n;
vector<vector<int>> e;
vector<bool> ans;
TwoSat(int n) : n(n), e(2 * n), ans(n) {}
void add_clause(int u, bool f, int v, bool g) {
e[2 * u + !f].push_back(2 * v + g);
e[2 * v + !g].push_back(2 * u + f);
}
bool satisfiable() {
vector<int> id(2 * n, -1), dfn(2 * n, -1), low(2 * n, -1);
vector<int> stk;
int now = 0, cnt = 0;
function<void(int)> tarjan = [&](int u) {
stk.push_back(u);
dfn[u] = low[u] = now++;
for (auto v : e[u]) {
if (dfn[v] == -1) {
tarjan(v);
low[u] = min(low[u], low[v]);
}
else if (id[v] == -1) {
low[u] = min(low[u], dfn[v]);
}
}
if (dfn[u] == low[u]) {
int v;
do {
v = stk.back();
stk.pop_back();
id[v] = cnt;
} while (v != u);
cnt++;
}
};
for (int i = 0; i < 2 * n; i++) {
if (dfn[i] == -1) {
tarjan(i);
}
}
for (int i = 0; i < n; i++) {
if (id[2 * i] == id[2 * i + 1]) {
return false;
}
ans[i] = id[2 * i] > id[2 * i + 1];
}
return true;
}
vector<bool> answer() {
return ans;
}
};
void solve() {
int n, m;
cin >> n >> m;
TwoSat ts(n);
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
u--, v--;
bool f, g;
cin >> f >> g;
ts.add_clause(u, f, v, g);
}
if (ts.satisfiable()) {
cout << "YES\n";
vector<bool> ans = ts.answer();
for (int i = 0; i < n; i++) {
cout << ans[i] << " \n"[i == n - 1];
}
}
else {
cout << "NO\n";
}
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
return 0;
}