Bank app~30 min2s · 256 MBtarget O(2^n × n^2) time, O(2^n × n) spacedp
You work for a bank's internal audit team. The team must audit n ledgers, one after another, in some order, and every ledger is audited exactly once. The ledgers are numbered 0 to n - 1.
Some pairs of ledgers share an account manager. To keep the audit independent, two ledgers that share a manager must never be audited one right after the other.
Your team lead asks: "How many different audit orders respect that rule?" There are at most 13 ledgers.
Write count_audit_orders(n, conflicts).
n is the number of ledgers.conflicts[k] = [a, b] means ledgers a and b share a manager. It applies in both orders, and a != b.n ledgers. It is valid when no two neighbours in the order form a conflict.0 when there is none.Input: n = 4, conflicts = [[0, 1], [1, 2]]
Output: 4Ledger 1 clashes with 0 and with 2, so neither may sit next to it. Only ledger 3 can be its neighbour. Each digit is a ledger, in audit order. The valid orders are:
| Order | Neighbour pairs | Any clash? |
|---|---|---|
| 0231 | 0-2, 2-3, 3-1 | no |
| 1302 | 1-3, 3-0, 0-2 | no |
| 1320 | 1-3, 3-2, 2-0 | no |
| 2031 | 2-0, 0-3, 3-1 | no |
There are 4 valid orders, and the other 20 of the 24 orders put ledger 1 next to ledger 0 or 2.
Input: n = 1, conflicts = []
Output: 1One ledger has exactly one order.
Input: n = 2, conflicts = [[0, 1]]
Output: 0Both orders, 01 and 10, put the clashing ledgers side by side.
1 ≤ n ≤ 130 ≤ len(conflicts) ≤ 780 ≤ conflicts[k][0], conflicts[k][1] < n, and the two ledgers of a conflict differ.Trying every order takes 13! = 6,227,020,800 steps, which is too slow for a 2-second limit. But 2 to the power 13 is only 8,192. A method that works on the set of ledgers already audited has 8,192 sets, and a small amount of work for each.