-
Notifications
You must be signed in to change notification settings - Fork 0
/
two-sat.cpp
48 lines (44 loc) · 1.06 KB
/
two-sat.cpp
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
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);
}
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;
}
}t;