-
Notifications
You must be signed in to change notification settings - Fork 57
/
assignment4.cpp
106 lines (86 loc) · 2.14 KB
/
assignment4.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
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
// Implementation of Kosaraju's Algorithm to find
// Strongly Connected Components for 2 SAT problem
#include <bits/stdc++.h>
using namespace std;
const int MAX = 2000001;
vector<int> adj[MAX];
vector<int> adjInv[MAX];
bool visited[MAX];
bool visitedInv[MAX];
stack<int> s;
int scc[MAX];
int counter = 1;
void addEdges(int a, int b) {
adj[a].push_back(b);
}
void addEdgesInv(int a, int b) {
adjInv[b].push_back(a);
}
void dfs(int u) {
if (visited[u]) return;
visited[u] = 1;
for (int i = 0; i < adj[u].size(); i++) {
dfs(adj[u][i]);
}
s.push(u);
}
void dfsInv(int u) {
if (visitedInv[u]) return;
visitedInv[u] = 1;
for (int i = 0; i < adjInv[u].size(); i++) {
dfsInv(adjInv[u][i]);
}
scc[u] = counter;
}
int main() {
int n;
ifstream file("2sat6.txt");
file >> n;
int a, b;
while (file >> a >> b) {
if (a > 0 && b > 0) {
addEdges(a+n, b);
addEdgesInv(a+n, b);
addEdges(b+n, a);
addEdgesInv(b+n, a);
}
else if (a > 0 && b < 0) {
addEdges(a+n, n-b);
addEdgesInv(a+n, n-b);
addEdges(-b, a);
addEdgesInv(-b, a);
}
else if (a < 0 && b > 0) {
addEdges(-a, b);
addEdgesInv(-a, b);
addEdges(b+n, n-a);
addEdgesInv(b+n, n-a);
}
else {
addEdges(-a, n-b);
addEdgesInv(-a, n-b);
addEdges(-b, n-a);
addEdgesInv(-b, n-a);
}
}
for (int i = 1; i <= 2*n; i++) {
if (!visited[i]) dfs(i);
}
while (!s.empty()) {
int k = s.top();
s.pop();
if (!visitedInv[k]) {
dfsInv(k);
counter++;
}
}
bool satisfiable = true;
for (int i = 1; i <= n; i++) {
if (scc[i] == scc[i+n]) {
cout << "Unsatisfiable" << endl;
satisfiable = false;
break;
}
}
if (satisfiable) cout << "Satisfiable" << endl;
}