-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo sat.cpp
More file actions
106 lines (82 loc) · 2.48 KB
/
two sat.cpp
File metadata and controls
106 lines (82 loc) · 2.48 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
99
100
101
102
103
104
105
106
#include <bits/stdc++.h>
using namespace std;
///source : https://codeforces.com/blog/entry/92977
///problem: https://cses.fi/problemset/task/1684
struct two_sat {
int n;
vector<vector<int>> g, gr;
vector<int> comp, topological_order, answer;
vector<bool> vis;
two_sat() {}
two_sat(int _n) { init(_n); }
void init(int _n) {
n = _n;
g.assign(2 * n, vector<int>());
gr.assign(2 * n, vector<int>());
comp.resize(2 * n);
vis.resize(2 * n);
answer.resize(2 * n);
}
void add_edge(int u, int v) {
g[u].push_back(v);
gr[v].push_back(u);
}
// At least one of them is true
void add_clause_or(int i, bool f, int j, bool g) {
add_edge(i + (f ? n : 0), j + (g ? 0 : n));
add_edge(j + (g ? n : 0), i + (f ? 0 : n));
}
// Only one of them is true
void add_clause_xor(int i, bool f, int j, bool g) {
add_clause_or(i, f, j, g);
add_clause_or(i, !f, j, !g);
}
// Both of them have the same value
void add_clause_and(int i, bool f, int j, bool g) {
add_clause_xor(i, !f, j, g);
}
void dfs(int u) {
vis[u] = true;
for (const auto &v : g[u])
if (!vis[v]) dfs(v);
topological_order.push_back(u);
}
void scc(int u, int id) {
vis[u] = true;
comp[u] = id;
for (const auto &v : gr[u])
if (!vis[v]) scc(v, id);
}
bool satisfiable() {
fill(vis.begin(), vis.end(), false);
for (int i = 0; i < 2 * n; i++)
if (!vis[i]) dfs(i);
fill(vis.begin(), vis.end(), false);
reverse(topological_order.begin(), topological_order.end());
int id = 0;
for (const auto &v : topological_order)
if (!vis[v]) scc(v, id++);
for (int i = 0; i < n; i++) {
if (comp[i] == comp[i + n]) return false;
answer[i] = (comp[i] > comp[i + n] ? 1 : 0);
}
return true;
}
};
int main() {
int N, M;
cin >> N >> M;
two_sat solver(M);
while (N--) {
int topping1, topping2;
char preference1, preference2;
cin >> preference1 >> topping1 >> preference2 >> topping2;
solver.add_clause_or(topping1 - 1, preference1 == '+', topping2 - 1, preference2 == '+');
}
if (!solver.satisfiable()) {
cout << "IMPOSSIBLE";
return 0;
}
for (int i = 0; i < M; i++)
cout << (solver.answer[i] ? '+' : '-') << " ";
}