1919from itertools import combinations , combinations_with_replacement , product
2020
2121
22- def two_sat (
22+ def _implication_graph (
2323 number_of_variables : int , clauses : list [tuple [int , int ]]
24- ) -> list [bool ] | None :
25- """Return a satisfying assignment, or None if the 2-CNF formula is impossible .
24+ ) -> tuple [ list [list [ int ]], list [ list [ int ]]] :
25+ """Build the forward and reverse graphs for the clauses .
2626
27- The returned list contains the truth values of x1, x2, ..., xN in order.
28- For a satisfiable formula, more than one assignment may be valid .
27+ Each variable has two vertices: the positive literal at an even index
28+ and the negative literal at the next odd index. XOR 1 negates a literal .
2929
30- >>> two_sat(2, [(1, 2), (-1, 2), (1, -2)])
31- [True, True]
32- >>> two_sat(1, [(1, 1)])
33- [True]
34- >>> two_sat(1, [(-1, -1)])
35- [False]
36- >>> two_sat(1, [(1, 1), (-1, -1)]) is None
37- True
38- >>> two_sat(2, [(1, 2), (-1, 2), (1, -2), (-1, -2)]) is None
39- True
40- >>> two_sat(2, [(1, -1), (2, -2)])
41- [True, True]
42- >>> two_sat(0, [])
43- []
44- >>> two_sat(2, [])
45- [True, True]
46- >>> two_sat(2, [(0, 1)])
47- Traceback (most recent call last):
48- ...
49- ValueError: Literal 0 is outside the range 1..2
50- >>> two_sat(2, [(3, 1)])
51- Traceback (most recent call last):
52- ...
53- ValueError: Literal 3 is outside the range 1..2
54- >>> two_sat(-1, [])
55- Traceback (most recent call last):
56- ...
57- ValueError: Number of variables must be nonnegative
58- >>> two_sat(1, [(True, 1)])
59- Traceback (most recent call last):
60- ...
61- TypeError: Literals must be integers
30+ >>> _implication_graph(1, [(1, 1)])
31+ ([[], [0, 0]], [[1, 1], []])
6232 """
63- if isinstance (number_of_variables , bool ) or not isinstance (
64- number_of_variables , int
65- ):
66- msg = "Number of variables must be an integer"
67- raise TypeError (msg )
68- if number_of_variables < 0 :
69- msg = "Number of variables must be nonnegative"
70- raise ValueError (msg )
71-
7233 vertex_count = 2 * number_of_variables
7334 graph : list [list [int ]] = [[] for _ in range (vertex_count )]
7435 reversed_graph : list [list [int ]] = [[] for _ in range (vertex_count )]
@@ -82,27 +43,39 @@ def two_sat(
8243 msg = f"Literal { literal } is outside the range 1..{ number_of_variables } "
8344 raise ValueError (msg )
8445
85- # Positive and negative literals have consecutive indices; XOR 1
86- # switches between a literal and its negation.
8746 first_vertex = 2 * (abs (first ) - 1 ) + (first < 0 )
8847 second_vertex = 2 * (abs (second ) - 1 ) + (second < 0 )
89-
9048 for source , target in (
9149 (first_vertex ^ 1 , second_vertex ),
9250 (second_vertex ^ 1 , first_vertex ),
9351 ):
9452 graph [source ].append (target )
9553 reversed_graph [target ].append (source )
9654
97- # Kosaraju pass 1: collect vertices in DFS finishing order.
98- # Explicit stacks avoid Python's recursion limit for large formulas.
55+ return graph , reversed_graph
56+
57+
58+ def _kosaraju_components (
59+ graph : list [list [int ]], reversed_graph : list [list [int ]]
60+ ) -> list [int ]:
61+ """Find strongly connected components using two iterative DFS passes.
62+
63+ Both graphs must contain the same vertices and reversed edges.
64+
65+ >>> _kosaraju_components([[1], [0]], [[1], [0]])
66+ [0, 0]
67+ """
68+ vertex_count = len (graph )
9969 visited = [False ] * vertex_count
10070 finishing_order : list [int ] = []
71+
72+ # First pass: DFS finishing order in the original graph.
73+ # The explicit stack prevents recursion errors on long paths.
10174 for start in range (vertex_count ):
10275 if visited [start ]:
10376 continue
10477 visited [start ] = True
105- stack = [(start , 0 )] # (vertex, index of next outgoing edge)
78+ stack = [(start , 0 )]
10679 while stack :
10780 vertex , edge_index = stack [- 1 ]
10881 if edge_index == len (graph [vertex ]):
@@ -116,7 +89,7 @@ def two_sat(
11689 visited [neighbor ] = True
11790 stack .append ((neighbor , 0 ))
11891
119- # Kosaraju pass 2: label components in the reversed graph.
92+ # Second pass: visit the reversed graph in decreasing finishing order .
12093 components = [- 1 ] * vertex_count
12194 component_id = 0
12295 for start in reversed (finishing_order ):
@@ -131,6 +104,61 @@ def two_sat(
131104 components [neighbor ] = component_id
132105 stack_vertices .append (neighbor )
133106 component_id += 1
107+ return components
108+
109+
110+ def two_sat (
111+ number_of_variables : int , clauses : list [tuple [int , int ]]
112+ ) -> list [bool ] | None :
113+ """Return a satisfying assignment, or None if the 2-CNF formula is impossible.
114+
115+ The returned list contains the truth values of x1, x2, ..., xN in order.
116+ For a satisfiable formula, more than one assignment may be valid.
117+
118+ >>> two_sat(2, [(1, 2), (-1, 2), (1, -2)])
119+ [True, True]
120+ >>> two_sat(1, [(1, 1)])
121+ [True]
122+ >>> two_sat(1, [(-1, -1)])
123+ [False]
124+ >>> two_sat(1, [(1, 1), (-1, -1)]) is None
125+ True
126+ >>> two_sat(2, [(1, 2), (-1, 2), (1, -2), (-1, -2)]) is None
127+ True
128+ >>> two_sat(2, [(1, -1), (2, -2)])
129+ [True, True]
130+ >>> two_sat(0, [])
131+ []
132+ >>> two_sat(2, [])
133+ [True, True]
134+ >>> two_sat(2, [(0, 1)])
135+ Traceback (most recent call last):
136+ ...
137+ ValueError: Literal 0 is outside the range 1..2
138+ >>> two_sat(2, [(3, 1)])
139+ Traceback (most recent call last):
140+ ...
141+ ValueError: Literal 3 is outside the range 1..2
142+ >>> two_sat(-1, [])
143+ Traceback (most recent call last):
144+ ...
145+ ValueError: Number of variables must be nonnegative
146+ >>> two_sat(1, [(True, 1)])
147+ Traceback (most recent call last):
148+ ...
149+ TypeError: Literals must be integers
150+ """
151+ if isinstance (number_of_variables , bool ) or not isinstance (
152+ number_of_variables , int
153+ ):
154+ msg = "Number of variables must be an integer"
155+ raise TypeError (msg )
156+ if number_of_variables < 0 :
157+ msg = "Number of variables must be nonnegative"
158+ raise ValueError (msg )
159+
160+ graph , reversed_graph = _implication_graph (number_of_variables , clauses )
161+ components = _kosaraju_components (graph , reversed_graph )
134162
135163 assignment : list [bool ] = []
136164 for variable in range (number_of_variables ):
0 commit comments