forked from Ashishgup1/Competitive-Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2-SAT.cpp
79 lines (67 loc) · 1.28 KB
/
2-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
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
struct TwoSAT
{
static const int MAXV=1e5+5;
int n, cnt;
vector<int> g[MAXV], rg[MAXV]; //g=forward, rg=backward
bool vis[MAXV];
int order[MAXV], comp[MAXV];
void init(int curn)
{
n=curn;
for(int i=0;i<n;i++)
{
g[i].clear();
rg[i].clear();
}
}
void add(int u, int v)
{
g[u].push_back(v);
rg[v].push_back(u);
}
void dfs1(int u)
{
vis[u] = true;
for(auto it:g[u])
if(!vis[it])
dfs1(it);
order[cnt++] = u;
}
void dfs2(int u, int c)
{
comp[u] = c;
for(auto it:rg[u])
if(comp[it]==-1)
dfs2(it, c);
}
int solve(vector<int> &ans)
{
cnt=0;
memset(vis, 0, sizeof(vis));
for(int i=0;i<n;i++)
if(!vis[i])
dfs1(i);
memset(comp, -1, sizeof(comp));
int grp=0;
for(int i=n-1;i>=0;i--)
{
int u=order[i];
if(comp[u] == -1)
dfs2(u, grp++);
}
for(int i=0;i<n;i+=2)
if(comp[i]==comp[i^1])
return 0;
ans.clear();
for(int i=0;i<n;i+=2)
{
int choose = (comp[i] > comp[i^1]) ? i : (i^1);
ans.push_back(choose);
}
return 1;
}
};
Sample Problem 1: https://codeforces.com/contest/228/problem/E
Sample Solution 1: https://codeforces.com/contest/228/submission/39775751
Sample Problem 2: http://codeforces.com/contest/776/problem/D
Sample Solution 2: http://codeforces.com/contest/776/submission/39776230