问题
Find number of ways to create sequence A of length n satisfying m conditions. This sequence A should consist of only non negative numbers. Each condition is described by three integers (i,j,k) signifying max(A[i],A[j])=k.
It is guaranteed that each index of the sequence will be there in at least one condition i.e. there will be finite number of such sequences.
The maximum value of n will not exceed 18 and maximum value of k will not exceed 20000.
I tried it using dynamic programming but the time complexity came out to be exponential. Can you suggest me any better approach which will reduce the time complexity?
回答1:
Following user3386109's suggestion, decompose each input constraint max(A[i], A[j]) = k into three constraints:
- A[i] ≤ k
- A[j] ≤ k
- A[i] = k ∨ A[j] = k
We can count solutions using a DPLL-like backtracking procedure. First, the equivalent of unit propagation:
- Given two constraints A[i] ≤ k1 and A[i] ≤ k2, we can keep A[i] ≤ min(k1, k2) and discard the other.
- Given two constraints A[i] = k1 and A[i] ≤ k2, either we can drop the latter (if k1 ≤ k2) or declare that there are no solutions (otherwise).
- Given two constraints A[i] ≤ k1 and A[i] = k2 ∨ A[j] = k2, if k1 < k2, then we can simplify the latter to A[j] = k2.
- Given two constraints A[i] = k1 and A[i] = k2 ∨ A[j] = k2, either we can drop the latter (if k1 = k2) or simplify it to A[j] = k2 (otherwise).
If all constraints are of the first two types, we can count the number of solutions by taking the product of (k + 1) for each k that is the right-hand side of a non-redundant inequality constraint.
Otherwise, there is a constraint A[i] = k ∨ A[j] = k. We make two recursive calls: one with the extra constraint A[i] = k and one with the extra constraint A[i] ≤ k - 1 (we know that A[i] > k is impossible).
The depth of the recursive tree is at most n, since each child call fixes more variables than its parent after unit propagation. Hence the search tree has O(2n) nodes, each of which should be decently cheap.
来源:https://stackoverflow.com/questions/62784654/find-number-of-ways-to-create-sequence-a-of-length-n-satisfying-m-conditions