Skip to content

Commit 8b892d1

Browse files
author
Hamid Gasmi
committed
Issue #148: Implacation Graph and its Reversed graph are created
1 parent 02671ec commit 8b892d1

File tree

1 file changed

+30
-8
lines changed

1 file changed

+30
-8
lines changed

4-np-complete-problems/2-coping_with_np_completeness/2sat_circuit_design.py

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ def isSatisfiable_naive():
2222
class ImplicationGraph:
2323
def __init__(self, n, clauses):
2424
self.adjacency_list = [[] for _ in range(2 * n)]
25-
self.reversed_adjacency_list = [[] for _ in range(2 * n)]
26-
self.build_adjacency_list(clauses)
25+
self.build_adjacency_list(n, clauses)
26+
self.build_reversed_adjacency_list()
2727

2828
def sat_variables_count(self):
2929
len(self.adjacency_list) // 2
@@ -40,14 +40,36 @@ def vertices_count(self):
4040
def get_vertice_num(self, variable_num):
4141
return variable_num - 1 if variable_num > 0 else (-1) * variable_num - 1 + self.sat_variables_count()
4242

43-
# It will build 2 adjacency lists:
44-
# ... 1. 1st one corresponds to the implication graph G
45-
# ... 2. 2nd one corresponds to the reversed graph of G, Gr
46-
def build_adjacency_list(self, clauses):
43+
# Time Complexity: O(|C|)
44+
def build_adjacency_list(self, n, clauses):
4745

48-
for c in clauses):
49-
pass
46+
for c in clauses:
47+
l = c[0]
48+
v_non_l = self.get_vertice_num((-1) * l)
49+
v_l = self.get_vertice_num(l)
50+
if len(c) == 1:
51+
# (l): to create an edge from -l to l: -l --> l
52+
self.adjacency_list[v_non_l].append(v_l)
5053

54+
else:
55+
k = c[1]
56+
v_k = self.get_vertice_num(k)
57+
v_non_k = self.get_vertice_num((-1) * k)
58+
# (l V k): to create 2 edges from !l to k and !k to l:
59+
# ... !l --> k
60+
# ... !k --> l
61+
self.adjacency_list[v_non_l].append(self.get_vertice_num(v_k))
62+
self.adjacency_list[v_non_k].append(self.get_vertice_num(v_l))
63+
64+
# Time Complexity: O(|E|) = O(|Edges|) = O(2 |Clauses|) = O(|C|)
65+
def build_reversed_adjacency_list(self):
66+
67+
self.reversed_adjacency_list = [[] for _ in range(self.vertices_count())]
68+
69+
for v in range(self.vertices_count()):
70+
for a in self.adjacency_list[v]:
71+
self.reversed_adjacency_list[a].append(v)
72+
5173
if __name__ == "__main__":
5274

5375
n, m = map(int, input().split())

0 commit comments

Comments
 (0)