The problem
A planner must answer n yes-or-no questions, numbered 1 to n. Each rule is a pair (a, b) of two conditions, and at least one of the two must hold. The number k stands for “question k is answered yes”, and −k for “question k is answered no”. Return a list of n values: True for yes and False for no, question k at position k − 1. If no list of answers keeps every rule, return None.
rules = [(1, 2), (-1, 3), (-2, -3), (1, -2)]
two_sat(3, rules) # [True, False, True]
two_sat(3, rules + [(-1, 2)]) # None
The rule (-1, 3) reads: question 1 is no, or question 3 is yes (or both). A rule may name the same condition twice, (2, 2), which means question 2 must be yes. When several lists keep every rule, any of them is accepted: the tests check your list against every rule.
Limits
- Up to 50,000 questions and 100,000 rules.
- Trying every list of answers is far too slow (2⁴⁰ lists for 40 questions). The implication graph can hold a path 100,000 vertices long. The big tests have 4 seconds each.
Builds on CONN-4 2-SAT.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | No answer | Not run | |
| 3 | A rule with one condition twice | Not run | |
| 4 | Forced both ways | Not run | |
| 5 | Always true | Not run | |
| 6 | No rules | Not run | |
| 7 | Yes is the wrong first guess | Not run | |
| 8 | A chain that forces everything | Not run | |
| 9 | 40 questions | Not run | |
| 10 | 50,000 questions, 100,000 rules | Not run | |
| 11 | A forced chain of 50,000 | Not run | |
| 12 | A chain of 50,000 that closes | Not run | |
| 13 | A chain that forbids the last | Not run |