Find number of ways to create sequence A of length n satisfying m conditions

后端 未结 1 1911
心在旅途
心在旅途 2021-01-25 02:25

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 i

1条回答
  •  醉梦人生
    2021-01-25 03:05

    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.

    0 讨论(0)
提交回复
热议问题